Skip to content

Commit

Permalink
feat(json): support force mode in jsonModify
Browse files Browse the repository at this point in the history
  • Loading branch information
mirek committed Aug 17, 2023
1 parent 8112078 commit 9f755c9
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 8 deletions.
14 changes: 14 additions & 0 deletions src/json-modify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,17 @@ test('jsonModify', () => {
)
`))
})

test('jsonModify force', () => {
expect(Tsql.jsonModify(Tsql.raw('fooJson'), { 'force ref': null }).toString()).toEqual(Tsql.demargin(`
json_modify(
json_modify(
fooJson,
N'lax $.ref',
cast(1 as bit)
),
N'strict $.ref',
null
)
`))
})
31 changes: 24 additions & 7 deletions src/json-modify.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,35 @@
import auto from './auto.js'
import jsonPath from './json-path.js'
import trueValue from './true-value.js'
import tsql from './template.js'
import type S from './sanitised.js'

export const jsonModify =
(target: S, kvs: Record<string, unknown>): S => {
const paths = Object.keys(kvs)
return paths.reduce((result, path) => tsql`
json_modify(
${result},
${jsonPath(path)},
${auto(kvs[path])}
)
`, target)
return paths.reduce((result, path) => {
if (path.startsWith('force ')) {
const path_ = path.slice('force '.length)
return tsql`
json_modify(
json_modify(
${result},
${'lax ' + jsonPath(path_)},
${trueValue}
),
${'strict ' + jsonPath(path_)},
${auto(kvs[path])}
)
`
}
return tsql`
json_modify(
${result},
${jsonPath(path)},
${auto(kvs[path])}
)
`
}, target)
}

export default jsonModify
9 changes: 8 additions & 1 deletion src/sql.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as Tsql from './index.js'
import Sql from './test/sql.js'
import type * as Tsql from './index.js'

let sql: Sql

Expand Down Expand Up @@ -142,3 +142,10 @@ describe('merge1n', () => {
})

})

test('force json mode', async () => {
await expect(sql.value`select ${Tsql.jsonModify(Tsql.auto({ foo: 1 }), { 'force bar': null })}`).resolves.toEqual(JSON.stringify({
foo: 1,
bar: null
}))
})

0 comments on commit 9f755c9

Please sign in to comment.