Files
bodyshop/server/notifications/eventParser.js

67 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Parses an event by comparing old and new data to determine which fields have changed.
*/
const eventParser = async ({ oldData, newData, trigger, table, jobIdField }) => {
const isNew = !oldData;
let changedFields = {};
let changedFieldNames = [];
if (isNew) {
// If there's no old data, every field in newData is considered new
changedFields = Object.fromEntries(
Object.entries(newData).map(([key, value]) => [key, { old: undefined, new: value }])
);
changedFieldNames = Object.keys(newData);
} else {
// Compare oldData with newData for changes
for (const key in newData) {
if (Object.prototype.hasOwnProperty.call(newData, key)) {
// Check if the key exists in oldData and if values differ
if (
!Object.prototype.hasOwnProperty.call(oldData, key) ||
JSON.stringify(oldData[key]) !== JSON.stringify(newData[key])
) {
changedFields[key] = {
old: oldData[key], // Could be undefined if key didnt exist in oldData
new: newData[key]
};
changedFieldNames.push(key);
}
}
}
// Check for fields that were removed
for (const key in oldData) {
if (Object.prototype.hasOwnProperty.call(oldData, key) && !Object.prototype.hasOwnProperty.call(newData, key)) {
changedFields[key] = {
old: oldData[key],
new: null // Indicate field was removed
};
changedFieldNames.push(key);
}
}
}
// Extract jobId based on jobIdField
let jobId = null;
if (jobIdField) {
let keyName = jobIdField;
const prefix = "req.body.event.new.";
if (keyName.startsWith(prefix)) {
keyName = keyName.slice(prefix.length);
}
jobId = newData[keyName] || (oldData && oldData[keyName]) || null;
}
return {
changedFieldNames,
changedFields,
isNew,
data: newData,
trigger,
table,
jobId
};
};
module.exports = eventParser;