Ajv extra is a drop in replacement for ajv with extra goods.
Installation
const Ajv = require('@geoblink/ajv-extra')
const ajv = new Ajv({ allErrors: true })
const schema = { /*** a valid JSON schema ***/ }
validator = ajv.compile(schema)
const isValid = validator({ /*** JSON object to be validated ***/})
OneOfByKey
Sometimes the schema is parametrized by some information. For example:
const schema = {
type: 'object',
required: ['data'],
properties: {
data: {
oneOf: [
{
type: 'object',
properties: {
origin: {
enum: ['external']
},
/** some external properties **/
}
},
{
type: 'object',
properties: {
origin: {
enum: ['internal']
},
/** some external properties **/
}
},
]
}
}
}
In the previous example, we receive data that can be either internal or external with a schema that depends on origin. This schema is nice to work with because data is always present. Depending on the origin we'll have one or the other.
However, there is a big hindrance. Logs are really ugly. If we are given:
const obj = {
data: {
origin: 'internal',
/** wrong properties for internal **/
}
}
ajv has will show the logs for internal and external, although we are only interested in the internal properties. To solve this problem, we can use oneOfByKey
which has a very similar syntax
const schema = {
type: 'object',
required: ['data'],
properties: {
data: {
oneOfByKey: {
key: 'origin',
oneOf: [
{
type: 'object',
properties: {
origin: {
enum: ['external']
},
/** some external properties **/
}
},
{
type: 'object',
properties: {
origin: {
enum: ['internal']
},
/** some external properties **/
}
},
]
}
}
}
}
Now the validator knows that we are only interested in errors for internal properties