Created
October 15, 2018 14:18
-
-
Save bryzettler/f74df104f43f52a833a61c18d5683d88 to your computer and use it in GitHub Desktop.
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
import { Model } from 'objection'; | |
import { pick as _pick } from 'lodash'; | |
import User from './User'; | |
import utils from '../utils'; | |
export default class AuditLog extends Model { | |
static tableName = 'AuditLog'; | |
static jsonAttributes = []; | |
static jsonSchema = { | |
type: 'object', | |
properties: { | |
id: { type: ['integer', 'string'] }, | |
modelType: { type: 'string' }, | |
modelId: { type: ['integer', 'string'] }, | |
verb: { type: 'string' }, | |
originalData: { type: ['object', 'null'] }, | |
changedData: { type: ['object', 'null'] }, | |
changedBy: { type: ['integer', 'string'] }, | |
changedAt: { type: 'string' }, | |
}, | |
}; | |
async $afterGet(queryContext) { | |
await super.$afterGet(queryContext); | |
const creator = ( | |
await User | |
.query(queryContext.transaction) | |
.skipUndefined() | |
.where('id', '=', this.createdBy) | |
.first() | |
); | |
this.creator = creator; | |
} | |
static async log(transaction, { verb, model, updatedModel = {} }) { | |
const allowedKeys = model.constructor.auditKeys; | |
const changedData = ({ | |
...utils.objDeepDiff( | |
_pick(model.constructor.auditSanitize({ ...updatedModel }), allowedKeys), | |
_pick(model.constructor.auditSanitize({ ...model }), allowedKeys), | |
), | |
}); | |
if (Object.keys(changedData).length > 0 || verb === 'insert') { | |
await AuditLog | |
.query(transaction) | |
.insert({ | |
verb, | |
modelType: model.constructor.name, | |
modelId: model.$id(), | |
changedBy: updatedModel.updatedBy || model.createdBy, | |
originalData: { ...model }, | |
changedData, | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment