简体   繁体   中英

track changes in table nodejs

How can I track changes in table, using node js? For connection I use Sequelize. The task is watch user data changes and emmit event to frontend if there was changes. I use socket io, and don`t wont use timeout. Is there the way to track event like 'table field xxx where user_id = yyy was changed' and got new field value.

Try hooks in sequelize. In your conf/connection.js you can define global hooks. In this way you can intercept everything.

hooks definition:

const hooks = {
beforeBulkUpdate: (options) => {
    options.individualHooks = true;
    return;
},
beforeBulkDestroy: (options) => {
    options.individualHooks = true;
    return;
},
beforeCreate: (instance, options) => {
    sails.log.info(("%s %s"), 'beforeCreate', instance.$modelOptions.tableName);

    return;
},
beforeUpdate: (instance, options) => {
    sails.log.info(("%s %s"), 'beforeUpdate', instance.$modelOptions.tableName);

    var payload = {
        before: instance._previousDataValues,
        after: instance.dataValues,
        changed: instance._changed
    };
    ----> here you can write on the web socket
    return;
},
beforeDestroy: (instance, options) => {
    sails.log.info(("%s %s"), 'beforeDestroy', instance.$modelOptions.tableName);

    return;
}

}

connection:

mydb: {
    user: 'myuser',
    password: 'mypassword',
    database: 'mydatabase',
    options: {
        dialect: 'mysql',
        host: 'myhost',
        logging: true,
        define: {
            hooks: hooks
        }
    }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM