Don't redact null or undefined

This commit is contained in:
Johannes Marbach
2026-06-24 13:35:44 +02:00
parent a47c1536fc
commit e7397a41db
2 changed files with 32 additions and 2 deletions

View File

@@ -34,3 +34,25 @@ test("no redaction of unrelated keys", () => {
bar: "foo",
});
});
test("no redaction of missing keys", () => {
expect(
redact({ foo: "bar" } as { foo: string; bar: string | undefined }, "bar"),
).to.deep.equal({
foo: "bar",
});
});
test("no redaction of null values", () => {
expect(redact({ foo: "bar", bar: null }, "bar")).to.deep.equal({
foo: "bar",
bar: null,
});
});
test("no redaction of undefined values", () => {
expect(redact({ foo: "bar", bar: undefined }, "bar")).to.deep.equal({
foo: "bar",
bar: undefined,
});
});

View File

@@ -12,6 +12,14 @@ Please see LICENSE in the repository root for full details.
* @param keys Keys to be redacted in the object
* @returns A new object with the specified properties redacted
*/
export function redact<T extends object>(obj: T, ...keys: (keyof T)[]): T {
return { ...obj, ...Object.fromEntries(keys.map((k) => [k, "<redacted>"])) };
export function redact<T extends object>(
obj: T,
...keys: (keyof T)[]
): Record<keyof T, unknown> {
const result: Record<keyof T, unknown> = { ...obj };
for (const key of keys)
if (key in result && result[key] != null) {
result[key] = "<redacted>";
}
return result;
}