Add transaction logging

This commit is contained in:
Evan Morikawa 2016-06-20 16:03:14 -07:00
parent 83dfb664e1
commit 8ed94442c4
3 changed files with 55 additions and 0 deletions

View file

@ -1,6 +1,7 @@
const Sequelize = require('sequelize');
const fs = require('fs');
const path = require('path');
const TransactionLog = require('./transaction-log')
const STORAGE_DIR = path.join(__base, 'storage');
if (!fs.existsSync(STORAGE_DIR)) {
@ -69,6 +70,9 @@ class DatabaseConnectionFactory {
db.sequelize = sequelize;
db.Sequelize = Sequelize;
const transactionLog = new TransactionLog(db);
transactionLog.setupSQLHooks(sequelize)
return sequelize.authenticate().then(() =>
sequelize.sync()
).thenReturn(db);

View file

@ -0,0 +1,18 @@
module.exports = (sequelize, Sequelize) => {
const Transaction = sequelize.define('Transaction', {
type: Sequelize.STRING,
objectId: Sequelize.STRING,
modelName: Sequelize.STRING,
changedFields: {
type: Sequelize.STRING,
get: function get() {
return JSON.parse(this.getDataValue('changedFields'))
},
set: function set(val) {
this.setDataValue('changedFields', JSON.stringify(val));
},
},
});
return Transaction;
};

33
core/transaction-log.js Normal file
View file

@ -0,0 +1,33 @@
class TransactionLog {
constructor(db) {
this.db = db;
}
parseHookData({dataValues, _changed, $modelOptions}) {
return {
objectId: dataValues.id,
modelName: $modelOptions.name.singular,
changedFields: _changed,
}
}
isTransaction({$modelOptions}) {
return $modelOptions.name.singular === "Transaction"
}
transactionLogger(type) {
return (sequelizeHookData) => {
if (this.isTransaction(sequelizeHookData)) return;
this.db.Transaction.create(Object.assign({type: type},
this.parseHookData(sequelizeHookData)
));
}
}
setupSQLHooks(sequelize) {
sequelize.addHook("afterCreate", this.transactionLogger("create"))
sequelize.addHook("afterUpdate", this.transactionLogger("update"))
sequelize.addHook("afterDelete", this.transactionLogger("delete"))
}
}
module.exports = TransactionLog