Mailspring/packages/nylas-core/hook-transaction-log.js

36 lines
1.1 KiB
JavaScript
Raw Normal View History

const _ = require('underscore')
2016-06-24 07:28:51 +08:00
const PubsubConnector = require('./pubsub-connector')
module.exports = (db, sequelize) => {
const isTransaction = ($modelOptions) => {
return $modelOptions.name.singular === "transaction"
}
const allIgnoredFields = (changedFields) => {
const IGNORED_FIELDS = ["syncState", "version"];
return _.difference(Object.keys(changedFields), IGNORED_FIELDS).length === 0
}
const transactionLogger = (event) => {
return ({dataValues, _changed, $modelOptions}) => {
if ((isTransaction($modelOptions) || allIgnoredFields(_changed))) {
return;
}
2016-06-24 07:28:51 +08:00
const transactionData = Object.assign({event}, {
object: $modelOptions.name.singular,
objectId: dataValues.id,
changedFields: Object.keys(_changed),
});
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"))
sequelize.addHook("afterUpdate", transactionLogger("modify"))
2016-06-24 07:28:51 +08:00
sequelize.addHook("afterDelete", transactionLogger("delete"))
}