Skip to content

Commit

Permalink
Fix transform function logic for deeply nested jsonb (#530)
Browse files Browse the repository at this point in the history
* Refactor createJsonTransform logic

* Add tests for deeply nested json

* Remove test for deeply nested json

* Nested object test

* Add Nested array test
  • Loading branch information
Eprince-hub authored and porsager committed Feb 1, 2023
1 parent 1525f32 commit 758e986
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down
40 changes: 40 additions & 0 deletions tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 758e986

Please sign in to comment.