Skip to content

Instantly share code, notes, and snippets.

@tlumko
Created August 27, 2018 13:06
Show Gist options
  • Save tlumko/7ec5bc7c00e03d46a54132fd2f2dca8c to your computer and use it in GitHub Desktop.
Save tlumko/7ec5bc7c00e03d46a54132fd2f2dca8c to your computer and use it in GitHub Desktop.
Node sequelize audit log
const AuditLog = auditLogDb.define('audit-log', {
userId: {
type: Sequelize.DataTypes.INTEGER,
allowNull: true,
},
actionType: {
type: Sequelize.DataTypes.STRING,
allowNull: false,
},
table: {
type: Sequelize.DataTypes.STRING,
allowNull: false,
},
prevValues: {
type: Sequelize.DataTypes.TEXT,
allowNull: false,
},
newValues: {
type: Sequelize.DataTypes.TEXT,
allowNull: false,
}
}, {
updatedAt: false,
});
const options = {
hooks: {
afterCreate: (instance, options) => {
saveAuditLog('create', instance, options)
},
afterUpdate: (instance, options) => {
saveAuditLog('update', instance, options);
},
}
};
function saveAuditLog(action, model, options) {
AuditLog.create({
userId: options.userId,
actionType: action,
table: model._modelOptions.name.plural,
prevValues: JSON.stringify(_.pick(model._previousDataValues, model.attributes)),
newValues: JSON.stringify(_.pick(model.dataValues, model.attributes)),
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment