'ajv addSchema and validate the data doesn't fail with intentional test to fail
I am using https://ajv.js.org/ to validate schemas and the configuration.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"things": {
"type": "array",
"minItems": 0,
"uniqueItems": true,
"items": {
"$ref": "#/definitions/thing"
}
}
},
"definitions": {
"thing": {
"type": "object",
"required": [
"name",
"type",
"label"
],
"properties": {
"name": {
"type": "string",
"description": "Thing name"
},
"type": {
"enum": [
"THING1",
"THING2",
"THING3",
"THING4"
],
"description": "Thing type"
},
"label": {
"type": "string",
"description": "label to display for the thing"
}
}
}
}
}
The data to test is:
let data = {
"things": [
{
"type": "THING1",
"label": "Context navigate test"
}
]
}
when running validate(data) it fails which is expected
[
{
instancePath: '/things/0',
schemaPath: '#/definitions/thing/required',
keyword: 'required',
params: { missingProperty: 'name' },
message: "must have required property 'name'"
}
]
When I move the definitions to a file it doesn't fail anymore. Definition now in a file directory /definitions/thing_schema.json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "definitions/thing_schema.json#/thing",
"definitions": {
"thing": {
"description": "A representation of a thing",
"type": "object",
"required": [
"name",
"type",
"label"
],
"properties": {
"name": {
"type": "string",
"description": "Thing name"
},
"type": {
"enum": [
"THING1",
"THING2",
"THING3",
"THING4"
],
"description": "Thing type"
},
"label": {
"type": "string",
"description": "label to display for the thing"
}
}
}
}
}
The schema is now referencing the file instead of referencing the definition in its own file.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"things": {
"type": "array",
"minItems": 0,
"uniqueItems": true,
"items": {
"$ref": "definitions/thing_schema.json#/thing"
}
}
}
}
This time the validation doesn't fail.
ajv.addSchema(thingDefintionFile)
const validate = ajv.compile(schemaFile)
if(!validate(data)) {
console.log(validate.errors)
}
Solution 1:[1]
I have solved it.
"$ref": "things#/definitions/thing"
and changing the file definition to
"$id": "things",
I didn't reference it correctly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | joe |
