Skip to content

Commit 996b659

Browse files
committed
const is validated by fjs
1 parent 9e21900 commit 996b659

File tree

2 files changed

+130
-123
lines changed

2 files changed

+130
-123
lines changed

index.js

Lines changed: 47 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -785,26 +785,56 @@ function buildSingleTypeSerializer (location, input) {
785785

786786
function buildConstSerializer (location, input) {
787787
const schema = location.schema
788-
const type = schema.type
789-
790-
const hasNullType = Array.isArray(type) && type.includes('null')
791-
788+
let schemaRef = location.getSchemaRef()
789+
if (schemaRef.startsWith(rootSchemaId)) {
790+
schemaRef = schemaRef.replace(rootSchemaId, '')
791+
}
792792
let code = ''
793793

794-
if (hasNullType) {
795-
code += `
796-
if (${input} === null) {
797-
json += 'null'
794+
switch (typeof schema.const) {
795+
case 'bigint':
796+
code += `
797+
if (${input} === ${schema.const}n) {
798+
json += '${Number(schema.const)}'
798799
} else {
799-
`
800-
}
801-
802-
code += `json += '${JSON.stringify(schema.const)}'`
803-
804-
if (hasNullType) {
805-
code += `
800+
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
801+
}`
802+
break
803+
case 'number':
804+
case 'boolean':
805+
code += `
806+
if (${input} === ${schema.const}) {
807+
json += ${JSON.stringify(JSON.stringify(schema.const))}
808+
} else {
809+
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
810+
}`
811+
break
812+
case 'object':
813+
if (schema.const === null) {
814+
code += `
815+
if (${input} === null) {
816+
json += 'null'
817+
} else {
818+
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
819+
}`
820+
} else {
821+
code += `
822+
if (JSON.stringify(${input}) === '${JSON.stringify(schema.const)}') {
823+
json += ${JSON.stringify(JSON.stringify(schema.const))}
824+
} else {
825+
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
826+
}`
806827
}
807-
`
828+
break
829+
case 'string':
830+
case 'undefined':
831+
code += `
832+
if (${input} === '${schema.const}') {
833+
json += ${JSON.stringify(JSON.stringify(schema.const))}
834+
} else {
835+
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
836+
}`
837+
break
808838
}
809839

810840
return code
@@ -869,7 +899,7 @@ function buildValue (location, input) {
869899
return code
870900
}
871901

872-
const nullable = schema.nullable === true
902+
const nullable = schema.nullable === true && !('const' in schema)
873903
if (nullable) {
874904
code += `
875905
if (${input} === null) {

0 commit comments

Comments
 (0)