chore(backend.js): json processing optimisations

This commit is contained in:
Rim 2025-04-16 16:18:12 -04:00
parent b6921dcbde
commit fe2ab59aaf

View File

@ -25,36 +25,41 @@ try {
logger.error('Error loading replacements file:', { error: error.message });
}
// Optimized replaceJsonKeys function
const replaceJsonKeys = (obj) => {
if (!obj || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) {
return obj.map((item) => replaceJsonKeys(item));
}
const newObj = {};
Object.keys(obj).forEach((key) => {
// Replace key if it exists in replacements
const newKey = keyReplacements[key] || key;
// DEBUG: Log replacements when they happen
// if (newKey !== key) {
// logger.debug(`Replacing key "${key}" with "${newKey}"`);
// }
// Also check if the value should be replaced (if it's a string)
let value = obj[key];
if (typeof value === 'string' && keyReplacements[value]) {
value = keyReplacements[value];
// logger.debug(`Replacing value "${obj[key]}" with "${value}"`);
if (!obj || typeof obj !== 'object') return obj;
// Fast-path for arrays
if (Array.isArray(obj)) {
// Only process array if it has items
return obj.length > 0 ? obj.map(replaceJsonKeys) : obj;
}
// Process value recursively if it's an object or array
newObj[newKey] = replaceJsonKeys(value);
});
return newObj;
};
const newObj = {};
const objKeys = Object.keys(obj);
// Fast-path for empty objects
if (objKeys.length === 0) return obj;
// Cache key check
const hasKeyReplacements = Object.keys(keyReplacements).length > 0;
for (const key of objKeys) {
// Replace key if replacements exist
const newKey = hasKeyReplacements && keyReplacements[key] ? keyReplacements[key] : key;
let value = obj[key];
// Replace string values if needed
if (hasKeyReplacements && typeof value === 'string' && keyReplacements[value]) {
value = keyReplacements[value];
}
// Process recursively only if object/array
newObj[newKey] = (value && typeof value === 'object') ? replaceJsonKeys(value) : value;
}
return newObj;
};
// Utility regex function
const sanitizeJsonOutput = (data) => {