Skip to content

Instantly share code, notes, and snippets.

@bryzettler
Created October 15, 2018 14:18
Show Gist options
  • Save bryzettler/f74df104f43f52a833a61c18d5683d88 to your computer and use it in GitHub Desktop.
Save bryzettler/f74df104f43f52a833a61c18d5683d88 to your computer and use it in GitHub Desktop.
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