From 758e986aee50f7a55862c31d12d85b0bc1d4a739 Mon Sep 17 00:00:00 2001 From: Victor Ejike Nwosu <74430629+Eprince-hub@users.noreply.github.com> Date: Tue, 3 Jan 2023 12:58:51 +0100 Subject: [PATCH] Fix transform function logic for deeply nested jsonb (#530) * Refactor createJsonTransform logic * Add tests for deeply nested json * Remove test for deeply nested json * Nested object test * Add Nested array test --- src/types.js | 5 ++++- tests/index.js | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/types.js b/src/types.js index 75c1a498..b69954d9 100644 --- a/src/types.js +++ b/src/types.js @@ -328,7 +328,10 @@ function createJsonTransform(fn) { return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x) ? x.map(x => jsonTransform(x, column)) - : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: v }), {}) + : Object.entries(x).reduce((acc, [k, v]) => { + const transformedKey = fn(k) + return Object.assign(acc, { [transformedKey]: jsonTransform(v, column) }) + }, {}) : x } } diff --git a/tests/index.js b/tests/index.js index 173c7cf8..2c43b9e1 100644 --- a/tests/index.js +++ b/tests/index.js @@ -612,6 +612,46 @@ t('Transform nested json in arrays', async() => { return ['aBcD', (await sql`select '[{"a_b":1},{"c_d":2}]'::jsonb as x`)[0].x.map(Object.keys).join('')] }) +t('Transform deeply nested json object in arrays', async() => { + const sql = postgres({ + ...options, + transform: postgres.camel + }) + return ['childObj_deeplyNestedObj_grandchildObj', (await sql`select '[{"nested_obj": {"child_obj": 2, "deeply_nested_obj": {"grandchild_obj": 3}}}]'::jsonb as x`)[0].x + .map((x) => { + let result; + for (const key in x) { + const result1 = Object.keys(x[key]); + const result2 = Object.keys(x[key].deeplyNestedObj); + + result = [...result1, ...result2]; + } + + return result; + })[0] + .join('_')] +}) + +t('Transform deeply nested json array in arrays', async() => { + const sql = postgres({ + ...options, + transform: postgres.camel + }) + return ['childArray_deeplyNestedArray_grandchildArray', (await sql`select '[{"nested_array": [{"child_array": 2, "deeply_nested_array": [{"grandchild_array":3}]}]}]'::jsonb AS x`)[0].x + .map((x) => { + let result; + for (const key in x) { + const result1 = Object.keys(x[key][0]); + const result2 = Object.keys(x[key][0].deeplyNestedArray[0]); + + result = [...result1, ...result2]; + } + + return result; + })[0] + .join('_')] +}) + t('Bypass transform for json primitive', async() => { const sql = postgres({ ...options,