chore(backend.js): json processing optimisations
This commit is contained in:
parent
b6921dcbde
commit
fe2ab59aaf
@ -25,36 +25,41 @@ try {
|
|||||||
logger.error('Error loading replacements file:', { error: error.message });
|
logger.error('Error loading replacements file:', { error: error.message });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Optimized replaceJsonKeys function
|
||||||
const replaceJsonKeys = (obj) => {
|
const replaceJsonKeys = (obj) => {
|
||||||
if (!obj || typeof obj !== 'object') return obj;
|
if (!obj || typeof obj !== 'object') return obj;
|
||||||
|
|
||||||
if (Array.isArray(obj)) {
|
// Fast-path for arrays
|
||||||
return obj.map((item) => replaceJsonKeys(item));
|
if (Array.isArray(obj)) {
|
||||||
}
|
// Only process array if it has items
|
||||||
|
return obj.length > 0 ? obj.map(replaceJsonKeys) : obj;
|
||||||
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}"`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process value recursively if it's an object or array
|
const newObj = {};
|
||||||
newObj[newKey] = replaceJsonKeys(value);
|
const objKeys = Object.keys(obj);
|
||||||
});
|
|
||||||
|
// Fast-path for empty objects
|
||||||
return newObj;
|
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
|
// Utility regex function
|
||||||
const sanitizeJsonOutput = (data) => {
|
const sanitizeJsonOutput = (data) => {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user