From 7bee57f7c55e15b6a6c847dfda433e67f258ef8e Mon Sep 17 00:00:00 2001 From: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com> Date: Sat, 2 Jul 2022 17:29:27 +0200 Subject: [PATCH] fix(medusa-js): Fix `stringifyNullProperties` util (#1766) **What** Changes the order of object type evaluation to properly handle null properties. Previously, `stringifyNullProperties({ test: null })` would fail in the 2nd iteration due to an attempt to iterate `null` in `Object.keys(obj)`. --- packages/medusa-js/src/utils.ts | 6 ++-- packages/medusa-js/test/utils/utils.test.ts | 31 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 packages/medusa-js/test/utils/utils.test.ts diff --git a/packages/medusa-js/src/utils.ts b/packages/medusa-js/src/utils.ts index 1dcf0936f1..3f0b6f0097 100644 --- a/packages/medusa-js/src/utils.ts +++ b/packages/medusa-js/src/utils.ts @@ -3,12 +3,10 @@ export function stringifyNullProperties(input: T): T { const res = {} as T Object.keys(obj).reduce((acc: T, key: string) => { - if (typeof obj[key] === "object") { - acc[key] = convertProperties(obj[key]) - } - if (obj[key] === null) { acc[key] = "null" + } else if (typeof obj[key] === "object") { + acc[key] = convertProperties(obj[key]) } else { acc[key] = obj[key] } diff --git a/packages/medusa-js/test/utils/utils.test.ts b/packages/medusa-js/test/utils/utils.test.ts new file mode 100644 index 0000000000..055bab6130 --- /dev/null +++ b/packages/medusa-js/test/utils/utils.test.ts @@ -0,0 +1,31 @@ +import { stringifyNullProperties } from "../../src/utils" + +describe("stringifyNullProperties", () => { + test("returns empty object on no props", () => { + const result = stringifyNullProperties({}) + expect(result).toEqual({}) + }) + + test("successfully stringifies null property", () => { + const result = stringifyNullProperties({ test: null }) + expect(result).toEqual({ test: "null" }) + }) + + test("successfully stringifies nested null property", () => { + const result = stringifyNullProperties({ + test: { test_2: { test_3: null } }, + another_test: "test", + }) + expect(result).toEqual({ + test: { test_2: { test_3: "null" } }, + another_test: "test", + }) + }) + + test("successfully stringifies string property", () => { + const result = stringifyNullProperties({ + test: "test", + }) + expect(result).toEqual({ test: "test" }) + }) +})