2020-10-22 09:24:53 +00:00
|
|
|
/**
|
|
|
|
* Translates to a readable values
|
|
|
|
* @param {Object} instance - The model or context instance
|
|
|
|
* @param {Object} changes - Object containing changes
|
|
|
|
*/
|
|
|
|
exports.translateValues = async(instance, changes) => {
|
|
|
|
const models = instance.app.models;
|
|
|
|
|
|
|
|
function getRelation(instance, property) {
|
|
|
|
const relations = instance.definition.settings.relations;
|
|
|
|
for (let relationName in relations) {
|
|
|
|
const relation = relations[relationName];
|
|
|
|
if (relation.foreignKey == property)
|
|
|
|
return relation;
|
|
|
|
}
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
function getValue(rawData) {
|
|
|
|
const row = JSON.parse(JSON.stringify(rawData));
|
|
|
|
for (column in row)
|
|
|
|
return row[column];
|
|
|
|
}
|
|
|
|
|
|
|
|
function formatDate(date) {
|
|
|
|
return new Intl.DateTimeFormat('es', {
|
|
|
|
year: '2-digit',
|
|
|
|
month: '2-digit',
|
|
|
|
day: '2-digit',
|
|
|
|
hour: '2-digit',
|
|
|
|
minute: '2-digit',
|
|
|
|
second: '2-digit'
|
|
|
|
}).format(date);
|
|
|
|
}
|
|
|
|
|
|
|
|
const properties = Object.assign({}, changes);
|
|
|
|
for (let property in properties) {
|
|
|
|
const relation = getRelation(instance, property);
|
|
|
|
const value = properties[property];
|
|
|
|
|
|
|
|
let finalValue = value;
|
|
|
|
if (relation) {
|
|
|
|
const model = relation.model;
|
|
|
|
const row = await models[model].findById(value, {
|
|
|
|
fields: ['alias', 'name', 'code', 'description']
|
|
|
|
});
|
|
|
|
const newValue = getValue(row);
|
|
|
|
if (newValue) finalValue = newValue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (finalValue instanceof Date)
|
|
|
|
finalValue = formatDate(finalValue);
|
|
|
|
|
|
|
|
properties[property] = finalValue;
|
|
|
|
}
|
|
|
|
|
|
|
|
return properties;
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the changes between two objects
|
2020-10-22 10:01:45 +00:00
|
|
|
* @param {Object} original - Original object
|
|
|
|
* @param {Object} changes - New changes
|
2020-10-22 09:24:53 +00:00
|
|
|
* @return {Object} Old and new values
|
|
|
|
*/
|
|
|
|
exports.getChanges = (original, changes) => {
|
|
|
|
const oldChanges = {};
|
|
|
|
const newChanges = {};
|
|
|
|
for (let property in changes) {
|
|
|
|
if (changes[property] != original[property]) {
|
|
|
|
newChanges[property] = changes[property];
|
|
|
|
|
|
|
|
if (original[property] != undefined)
|
|
|
|
oldChanges[property] = original[property];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
old: oldChanges,
|
|
|
|
new: newChanges
|
|
|
|
};
|
|
|
|
};
|