Skip to content

Instantly share code, notes, and snippets.

@anuraagdjain
Created December 26, 2024 10:16
Show Gist options
  • Save anuraagdjain/0e516f0070d4f26a330cb2776a11a769 to your computer and use it in GitHub Desktop.
Save anuraagdjain/0e516f0070d4f26a330cb2776a11a769 to your computer and use it in GitHub Desktop.
A quick method which generates a base64 hash string for a given object for the purpose of caching the API response in redis when the request parameters match.
function isObject(obj) {
return typeof obj==='object' && !Array.isArray(obj) && obj !== null;
}
// object -> array
function paramStrGen(obj){
var finalKey = [];
Object.keys(obj).sort().forEach(key => {
var val = obj[key];
var fval = Array.isArray(val) ? val.sort().join() : val;
finalKey.push(`${key}:${fval}`);
});
return finalKey;
}
// nested object -> array
function paramStrGenV2(obj,rootKey){
var finalKey = [];
Object.keys(obj).sort().forEach(key => {
var fkey = rootKey === null ? key : `${rootKey}.${key}`;
var val = obj[key];
if(isObject(val)){
// recursion to generate the array for inner objects.
finalKey = finalKey.concat(paramStrGenV2(val,fkey));
}else{
var fval = Array.isArray(val) ? val.sort().join() : val;
finalKey.push(`${fkey}:${fval}`);
}
});
return finalKey;
}
var crypto = require('node:crypto');
var ipobj = {x:1, y:true,a:["c","b","a"],n1:{x1:true,y:["z","c"],n2:{hello:"world",a3:{nested: true}}}};
var result = paramStrGenV2(ipobj,null);
console.log('Final array', result);
console.log(crypto.createHash('sha1').update(result.join()).digest('base64'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment