Skip to content

Commit a848ca6

Browse files
authored
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
1 parent f93d0d4 commit a848ca6

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/types.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,10 @@ function createJsonTransform(fn) {
332332
return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802)
333333
? Array.isArray(x)
334334
? x.map(x => jsonTransform(x, column))
335-
: Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: v }), {})
335+
: Object.entries(x).reduce((acc, [k, v]) => {
336+
const transformedKey = fn(k)
337+
return Object.assign(acc, { [transformedKey]: jsonTransform(v, column) })
338+
}, {})
336339
: x
337340
}
338341
}

tests/index.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -611,6 +611,46 @@ t('Transform nested json in arrays', async() => {
611611
return ['aBcD', (await sql`select '[{"a_b":1},{"c_d":2}]'::jsonb as x`)[0].x.map(Object.keys).join('')]
612612
})
613613

614+
t('Transform deeply nested json object in arrays', async() => {
615+
const sql = postgres({
616+
...options,
617+
transform: postgres.camel
618+
})
619+
return ['childObj_deeplyNestedObj_grandchildObj', (await sql`select '[{"nested_obj": {"child_obj": 2, "deeply_nested_obj": {"grandchild_obj": 3}}}]'::jsonb as x`)[0].x
620+
.map((x) => {
621+
let result;
622+
for (const key in x) {
623+
const result1 = Object.keys(x[key]);
624+
const result2 = Object.keys(x[key].deeplyNestedObj);
625+
626+
result = [...result1, ...result2];
627+
}
628+
629+
return result;
630+
})[0]
631+
.join('_')]
632+
})
633+
634+
t('Transform deeply nested json array in arrays', async() => {
635+
const sql = postgres({
636+
...options,
637+
transform: postgres.camel
638+
})
639+
return ['childArray_deeplyNestedArray_grandchildArray', (await sql`select '[{"nested_array": [{"child_array": 2, "deeply_nested_array": [{"grandchild_array":3}]}]}]'::jsonb AS x`)[0].x
640+
.map((x) => {
641+
let result;
642+
for (const key in x) {
643+
const result1 = Object.keys(x[key][0]);
644+
const result2 = Object.keys(x[key][0].deeplyNestedArray[0]);
645+
646+
result = [...result1, ...result2];
647+
}
648+
649+
return result;
650+
})[0]
651+
.join('_')]
652+
})
653+
614654
t('Bypass transform for json primitive', async() => {
615655
const sql = postgres({
616656
...options,

0 commit comments

Comments
 (0)