Created
August 27, 2018 13:06
-
-
Save tlumko/7ec5bc7c00e03d46a54132fd2f2dca8c to your computer and use it in GitHub Desktop.
Node sequelize audit log
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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