diff --git a/core/database-connection-factory.js b/core/database-connection-factory.js index 47d293c91..c054fd32a 100644 --- a/core/database-connection-factory.js +++ b/core/database-connection-factory.js @@ -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); diff --git a/core/models/account/transaction.js b/core/models/account/transaction.js new file mode 100644 index 000000000..6726e72c2 --- /dev/null +++ b/core/models/account/transaction.js @@ -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; +}; diff --git a/core/transaction-log.js b/core/transaction-log.js new file mode 100644 index 000000000..f636ac6f5 --- /dev/null +++ b/core/transaction-log.js @@ -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