2016-07-14 07:31:11 +08:00
|
|
|
const _ = require('underscore')
|
2016-06-24 07:28:51 +08:00
|
|
|
const PubsubConnector = require('./pubsub-connector')
|
|
|
|
|
|
|
|
module.exports = (db, sequelize) => {
|
2016-07-15 08:14:16 +08:00
|
|
|
const isTransaction = ($modelOptions) => {
|
|
|
|
return $modelOptions.name.singular === "transaction"
|
2016-07-14 07:31:11 +08:00
|
|
|
}
|
2016-07-09 06:33:37 +08:00
|
|
|
|
2016-07-15 08:14:16 +08:00
|
|
|
const allIgnoredFields = (changedFields) => {
|
2016-07-14 07:31:11 +08:00
|
|
|
const IGNORED_FIELDS = ["syncState", "version"];
|
2016-07-15 08:14:16 +08:00
|
|
|
return _.difference(Object.keys(changedFields), IGNORED_FIELDS).length === 0
|
2016-07-14 07:31:11 +08:00
|
|
|
}
|
2016-07-09 06:33:37 +08:00
|
|
|
|
2016-07-15 08:14:16 +08:00
|
|
|
const transactionLogger = (event) => {
|
|
|
|
return ({dataValues, _changed, $modelOptions}) => {
|
|
|
|
if ((isTransaction($modelOptions) || allIgnoredFields(_changed))) {
|
|
|
|
return;
|
|
|
|
}
|
2016-06-24 07:28:51 +08:00
|
|
|
|
2016-07-15 08:14:16 +08:00
|
|
|
const transactionData = Object.assign({event}, {
|
|
|
|
object: $modelOptions.name.singular,
|
|
|
|
objectId: dataValues.id,
|
|
|
|
changedFields: Object.keys(_changed),
|
|
|
|
});
|
2016-07-09 06:33:37 +08:00
|
|
|
|
2016-07-14 03:37:24 +08:00
|
|
|
db.Transaction.create(transactionData).then((transaction) => {
|
2016-07-15 07:28:03 +08:00
|
|
|
PubsubConnector.notifyDelta(db.accountId, transaction.toJSON());
|
2016-07-14 03:37:24 +08:00
|
|
|
})
|
2016-06-24 07:28:51 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
sequelize.addHook("afterCreate", transactionLogger("create"))
|
2016-07-15 08:14:16 +08:00
|
|
|
sequelize.addHook("afterUpdate", transactionLogger("modify"))
|
2016-06-24 07:28:51 +08:00
|
|
|
sequelize.addHook("afterDelete", transactionLogger("delete"))
|
|
|
|
}
|