Skip to content

Commit 758e986

Browse files
Eprince-hubporsager
authored andcommitted
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 1525f32 commit 758e986

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
@@ -328,7 +328,10 @@ function createJsonTransform(fn) {
328328
return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802)
329329
? Array.isArray(x)
330330
? x.map(x => jsonTransform(x, column))
331-
: Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: v }), {})
331+
: Object.entries(x).reduce((acc, [k, v]) => {
332+
const transformedKey = fn(k)
333+
return Object.assign(acc, { [transformedKey]: jsonTransform(v, column) })
334+
}, {})
332335
: x
333336
}
334337
}

tests/index.js

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

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

0 commit comments

Comments
 (0)