Last active
December 8, 2023 13:43
-
-
Save LeeCheneler/dff367bff2b9c6182dba19390e106278 to your computer and use it in GitHub Desktop.
Sanitize keys in an object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import crypto from "crypto"; | |
export const sanitize = (object: Record<string, unknown>, keysToHash: string[]): Record<string, unknown> => { | |
if (!object) { | |
return object; | |
} | |
const result: Record<string, unknown> = {}; | |
Object.entries(object).forEach(([key, value]) => { | |
if (!value) { | |
result[key] = value; | |
return; | |
} | |
if (keysToHash.includes(key)) { | |
result[key] = crypto.createHash("sha256").update(JSON.stringify(value)).digest("hex"); | |
return; | |
} | |
if (Array.isArray(value)) { | |
result[key] = value.map((item) => sanitize(item as Record<string, unknown>, keysToHash)); | |
return; | |
} | |
if (typeof value === "object" && !(value instanceof Date)) { | |
result[key] = sanitize(value as Record<string, unknown>, keysToHash); | |
return; | |
} | |
result[key] = value; | |
}); | |
return result; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const payload = { | |
id: 1, | |
name: "Lee", | |
}; | |
const sanitizedPayload = sanitize(payload, ["name"]); | |
console.log(sanitizedPayload); | |
// { id: 1, name: "<hash>" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment