Files
bodyshop/server/notifications/utils/eventParser.js
2025-02-10 15:19:41 -05:00

58 lines
1.8 KiB
JavaScript

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 changed (new)
changedFields = { ...newData };
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] = 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] = null; // Indicate field was removed
changedFieldNames.push(key);
}
}
}
// Extract jobId based on jobIdField
let jobId = null;
if (jobIdField) {
// If the jobIdField is provided as a string like "req.body.event.new.jobid",
// strip the prefix if it exists so we can use the property name.
let keyName = jobIdField;
const prefix = "req.body.event.new.";
if (keyName.startsWith(prefix)) {
keyName = keyName.slice(prefix.length);
}
// Attempt to retrieve the job id from newData first; if not available, try oldData.
jobId = newData[keyName] || (oldData && oldData[keyName]) || null;
}
return {
changedFieldNames,
changedFields,
isNew,
data: newData,
trigger,
table,
jobId
};
};
module.exports = eventParser;