Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ function buildMultiTypeSerializer (context, location, input) {
}
case 'integer': {
code += `
${statement}(Number.isInteger(${input}) || ${input} === null) {
${statement}(Number.isInteger(${input}) || typeof ${input} === 'bigint' || ${input} === null) {
${nestedResult}
}
`
Expand Down Expand Up @@ -1214,8 +1214,17 @@ function buildOneOf (context, location, input) {
const schemaRef = getValidatorSchemaRef(context, optionLocation)
context.validatorSchemaRefs.add(schemaRef)

// AJV does not recognise BigInt as type "integer".
// Pre-route BigInt to the first integer-typed schema so it reaches
// asInteger() (which correctly handles bigint) instead of falling
// through to the TypeError branch.
const isIntegerSchema = optionSchema.type === 'integer'
const condition = isIntegerSchema
? `typeof ${input} === 'bigint' || validator.validate("${schemaRef}", ${input})`
: `validator.validate("${schemaRef}", ${input})`

code += `
${index === 0 ? 'if' : 'else if'}(validator.validate("${schemaRef}", ${input})) {
${index === 0 ? 'if' : 'else if'}(${condition}) {
${nestedResult}
}
`
Expand Down
19 changes: 19 additions & 0 deletions test/typesArray.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,25 @@
t.assert.equal(value, '{"data":0}')
})


Check failure on line 69 in test/typesArray.test.js

View workflow job for this annotation

GitHub Actions / test / quality-check / Lint Code

More than 1 blank line not allowed
test('bigint serialized as integer in type array [integer, null]', (t) => {
t.plan(3)
const schema = { type: 'object', properties: { data: { type: ['integer', 'null'] } } }
const stringify = build(schema)
t.assert.equal(stringify({ data: 12n }), '{"data":12}')
t.assert.equal(stringify({ data: -5n }), '{"data":-5}')
t.assert.equal(stringify({ data: null }), '{"data":null}')
})

test('bigint serialized as integer in anyOf union', (t) => {
t.plan(3)
const schema = { type: 'object', properties: { data: { anyOf: [{ type: 'integer' }, { type: 'null' }] } } }
const stringify = build(schema)
t.assert.equal(stringify({ data: 12n }), '{"data":12}')
t.assert.equal(stringify({ data: -5n }), '{"data":-5}')
t.assert.equal(stringify({ data: null }), '{"data":null}')
})

test('possibly nullable number primitive alternative with null value', (t) => {
t.plan(1)

Expand Down
Loading