Skip to content

Commit

Permalink
Fix nested json array transform - fixes #506
Browse files Browse the repository at this point in the history
  • Loading branch information
porsager committed Oct 15, 2022
1 parent a12108a commit 5dea953
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/types.js
Expand Up @@ -331,7 +331,7 @@ function createJsonTransform(fn) {
return function jsonTransform(x, column) {
return column.type === 114 || column.type === 3802
? Array.isArray(x)
? x.map(jsonTransform)
? x.map(x => jsonTransform(x, column))
: Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: v }), {})

This comment has been minimized.

Copy link
@Eprince-hub

Eprince-hub Oct 19, 2022

Contributor

So I am installing Postgres from GitHub so I can try out this fix, and I realised that the transform function throws an error if null or undefined is passed to Object.entries()
Examples:

Object.entries(null)
Object.entries(undefined)

Throws

VM537:1 Uncaught TypeError: Cannot convert undefined or null to object
    at Function.entries (<anonymous>)
    at <anonymous>:1:8

In my case, I have a query that returns data like the example below

obj = {
id: 1,
name: 'Victor,
age: null
}

this causes the below error when it hits the Object.entries(x) part of the transform function
Screenshot 2022-10-19 at 10 14 15

I think checking for x before passing it to the Object.entries(x) would prevent this error. So we pass the data only when it is not undefined or null.
This worked for me when I changed that line of the transform function like this

- : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: v }), {})
+ : x && Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: v }), {})

I don't know if this is the proper fix, but it would be great if you look into this.
Thanks

: x
}
Expand Down
8 changes: 8 additions & 0 deletions tests/index.js
Expand Up @@ -603,6 +603,14 @@ t('column toKebab', async() => {
return ['hello-world', Object.keys((await sql`select * from test`)[0])[0], await sql`drop table test`]
})

t('Transform nested json in arrays', async() => {
const sql = postgres({
...options,
transform: postgres.camel
})
return ['aBcD', (await sql`select '[{"a_b":1},{"c_d":2}]'::jsonb as x`)[0].x.map(Object.keys).join('')]
})

t('unsafe', async() => {
await sql`create table test (x int)`
return [1, (await sql.unsafe('insert into test values ($1) returning *', [1]))[0].x, await sql`drop table test`]
Expand Down

0 comments on commit 5dea953

Please sign in to comment.