salix/loopback/common/models/loggable.js

276 lines
9.4 KiB
JavaScript
Raw Normal View History

2018-10-03 07:37:34 +00:00
const LoopBackContext = require('loopback-context');
const log = require('vn-loopback/util/log');
2018-10-03 07:37:34 +00:00
module.exports = function(Self) {
Self.setup = function() {
Self.super_.setup.call(this);
};
Self.observe('after save', async function(ctx) {
2018-10-03 07:37:34 +00:00
const loopBackContext = LoopBackContext.getCurrentContext();
await logInModel(ctx, loopBackContext);
});
Self.observe('before save', async function(ctx) {
const appModels = ctx.Model.app.models;
2020-05-26 13:49:20 +00:00
const definition = ctx.Model.definition;
const modelName = definition.name;
const model = appModels[modelName];
const options = {};
// Check for transactions
2019-02-27 09:56:31 +00:00
if (ctx.options && ctx.options.transaction)
options.transaction = ctx.options.transaction;
2018-10-03 07:37:34 +00:00
let oldInstance;
let newInstance;
2018-10-03 07:37:34 +00:00
if (ctx.data) {
const changes = log.getChanges(ctx.currentInstance, ctx.data);
oldInstance = await log.translateValues(model, changes.old, options);
newInstance = await log.translateValues(model, changes.new, options);
if (ctx.where && !ctx.currentInstance) {
const fields = Object.keys(ctx.data);
ctx.oldInstances = await appModels[modelName].find({
where: ctx.where,
fields: fields
}, options);
}
2018-10-03 07:37:34 +00:00
}
// Get changes from created instance
if (ctx.isNewInstance)
newInstance = await log.translateValues(model, ctx.instance.__data, options);
2018-10-03 07:37:34 +00:00
ctx.hookState.oldInstance = oldInstance;
ctx.hookState.newInstance = newInstance;
});
Self.observe('before delete', async function(ctx) {
const models = ctx.Model.app.models;
const definition = ctx.Model.definition;
const relations = ctx.Model.relations;
const options = {};
2019-02-27 09:56:31 +00:00
if (ctx.options && ctx.options.transaction)
options.transaction = ctx.options.transaction;
if (ctx.where) {
const modelName = definition.name;
const model = models[modelName];
const deletedRows = await model.find({
where: ctx.where
}, options);
const relation = definition.settings.log.relation;
if (relation) {
const primaryKey = relations[relation].keyFrom;
const instances = [];
for (let instance of deletedRows) {
const translatedValues = await log.translateValues(model, instance, options);
if (primaryKey)
translatedValues.originFk = instance[primaryKey];
instances.push(translatedValues);
}
ctx.hookState.oldInstance = instances;
}
2018-10-03 07:37:34 +00:00
}
});
Self.observe('after delete', async function(ctx) {
const loopBackContext = LoopBackContext.getCurrentContext();
if (ctx.hookState.oldInstance)
logDeletedInstances(ctx, loopBackContext);
});
async function logDeletedInstances(ctx, loopBackContext) {
const appModels = ctx.Model.app.models;
2020-05-26 13:49:20 +00:00
const definition = ctx.Model.definition;
2019-02-27 09:56:31 +00:00
let options = {};
if (ctx.options && ctx.options.transaction)
options.transaction = ctx.options.transaction;
ctx.hookState.oldInstance.forEach(async instance => {
let userFk;
if (loopBackContext)
userFk = loopBackContext.active.accessToken.userId;
let changedModelValue = definition.settings.log.changedModelValue;
let logRecord = {
originFk: instance.originFk,
userFk: userFk,
action: 'delete',
2020-05-26 13:49:20 +00:00
changedModel: definition.name,
changedModelId: instance.id,
changedModelValue: instance[changedModelValue],
oldInstance: instance,
newInstance: {}
};
delete instance.originFk;
let logModel = definition.settings.log.model;
await appModels[logModel].create(logRecord, options);
});
}
2018-10-03 07:37:34 +00:00
async function logInModel(ctx, loopBackContext) {
const appModels = ctx.Model.app.models;
const definition = ctx.Model.definition;
const defSettings = ctx.Model.definition.settings;
const relations = ctx.Model.relations;
const options = {};
2019-02-27 09:56:31 +00:00
if (ctx.options && ctx.options.transaction)
options.transaction = ctx.options.transaction;
2018-10-03 07:37:34 +00:00
let primaryKey;
for (let property in definition.properties) {
if (definition.properties[property].id) {
primaryKey = property;
break;
}
}
2018-10-03 07:37:34 +00:00
if (!primaryKey) throw new Error('Primary key not found');
let originId;
// RELATIONS LOG
let changedModelId;
if (ctx.instance && !defSettings.log.relation) {
originId = ctx.instance.id;
changedModelId = ctx.instance.id;
} else if (defSettings.log.relation) {
primaryKey = relations[defSettings.log.relation].keyFrom;
2018-10-03 07:37:34 +00:00
if (ctx.where && ctx.where[primaryKey])
originId = ctx.where[primaryKey];
else if (ctx.instance) {
2018-10-03 07:37:34 +00:00
originId = ctx.instance[primaryKey];
changedModelId = ctx.instance.id;
2018-10-03 07:37:34 +00:00
}
} else {
originId = ctx.currentInstance.id;
changedModelId = ctx.currentInstance.id;
2018-10-03 07:37:34 +00:00
}
// Sets the changedModelValue to save and the instances changed in case its an updateAll
let showField = defSettings.log.showField;
2019-02-27 09:56:31 +00:00
let where;
if (showField && (!ctx.instance || !ctx.instance[showField]) && ctx.where) {
changedModelId = [];
2019-02-27 09:56:31 +00:00
where = [];
let changedInstances = await appModels[definition.name].find({
where: ctx.where,
fields: ['id', showField, primaryKey]
}, options);
changedInstances.forEach(element => {
where.push(element[showField]);
changedModelId.push(element.id);
originId = element[primaryKey];
});
} else if (ctx.hookState.oldInstance)
where = ctx.instance[showField];
// Set oldInstance, newInstance, userFk and action
2018-10-03 07:37:34 +00:00
let oldInstance = {};
if (ctx.hookState.oldInstance)
2018-10-03 07:37:34 +00:00
Object.assign(oldInstance, ctx.hookState.oldInstance);
let newInstance = {};
if (ctx.hookState.newInstance)
Object.assign(newInstance, ctx.hookState.newInstance);
2018-10-03 10:54:13 +00:00
let userFk;
if (loopBackContext)
userFk = loopBackContext.active.accessToken.userId;
2018-10-03 10:54:13 +00:00
2018-10-03 07:37:34 +00:00
let action = setActionType(ctx);
2018-10-03 10:54:13 +00:00
removeUnloggable(definition, oldInstance);
removeUnloggable(definition, newInstance);
2019-09-12 07:49:02 +00:00
2020-06-04 12:44:38 +00:00
// Prevent log with no new changes
2020-06-04 12:46:55 +00:00
const hasNewChanges = Object.keys(newInstance).length;
2020-06-04 12:44:38 +00:00
if (!hasNewChanges) return;
2018-10-03 07:37:34 +00:00
let logRecord = {
originFk: originId,
userFk: userFk,
action: action,
changedModel: definition.name,
2020-01-21 08:00:42 +00:00
changedModelId: changedModelId, // Model property with an different data type will throw a NaN error
changedModelValue: where,
2018-10-03 07:37:34 +00:00
oldInstance: oldInstance,
newInstance: newInstance
};
let logsToSave = setLogsToSave(where, changedModelId, logRecord, ctx);
let logModel = defSettings.log.model;
2018-10-03 07:37:34 +00:00
await appModels[logModel].create(logsToSave, options);
}
2019-09-12 07:49:02 +00:00
/**
* Removes unwanted properties
* @param {*} definition Model definition
* @param {*} properties Modified object properties
*/
function removeUnloggable(definition, properties) {
2019-09-12 07:49:02 +00:00
const propList = Object.keys(properties);
const propDefs = new Map();
for (let property in definition.properties) {
const propertyDef = definition.properties[property];
propDefs.set(property, propertyDef);
}
for (let property of propList) {
const propertyDef = propDefs.get(property);
if (!propertyDef) return;
if (propertyDef.log === false)
delete properties[property];
else if (propertyDef.logValue === false)
properties[property] = null;
}
}
// this function retuns all the instances changed in case this is an updateAll
function setLogsToSave(changedInstances, changedInstancesIds, logRecord, ctx) {
let promises = [];
if (changedInstances && typeof changedInstances == 'object') {
for (let i = 0; i < changedInstances.length; i++) {
logRecord.changedModelId = changedInstancesIds[i];
logRecord.changedModelValue = changedInstances[i];
if (ctx.oldInstances)
logRecord.oldInstance = ctx.oldInstances[i];
promises.push(JSON.parse(JSON.stringify(logRecord)));
}
} else
return logRecord;
return promises;
2018-10-03 07:37:34 +00:00
}
function setActionType(ctx) {
const oldInstance = ctx.hookState.oldInstance;
const newInstance = ctx.hookState.newInstance;
2018-10-03 07:37:34 +00:00
if (oldInstance && newInstance)
2018-10-03 07:37:34 +00:00
return 'update';
else if (!oldInstance && newInstance)
2018-10-03 07:37:34 +00:00
return 'insert';
return 'delete';
2018-10-03 07:37:34 +00:00
}
};