Skip to content

Instantly share code, notes, and snippets.

@fgarcia
Last active February 13, 2019 14:20
Show Gist options
  • Save fgarcia/081a77518f33747fa61612a124c82d0b to your computer and use it in GitHub Desktop.
Save fgarcia/081a77518f33747fa61612a124c82d0b to your computer and use it in GitHub Desktop.
Central definition schema with AJV + dynamic definitions
// Objective: Define all schema definitions within a single schema '$id: core'
// + add definitions dynamically
it.only('extend Ajv definitions', async () => {
let res
let core1 = {
$id: 'core',
definitions: {
first: {
type: 'object',
properties: {
title: { type: 'string' },
},
additionalProperties: false,
},
},
}
let core2 = {
definitions: {
$id: 'core',
second: {
type: 'object',
properties: {
name: { type: 'string' },
value: { type: 'number' },
},
additionalProperties: false,
},
},
}
let schema = {
$id: 'demo',
type: 'object',
properties: {
x: { $ref: 'core#/definitions/first' },
y: { $ref: 'core#/definitions/second' },
},
}
var ajv = new Ajv({ schemas: [core1] })
res = ajv.getSchema('core')
res.schema.definitions.second = core2.definitions.second
ajv.addSchema(schema)
let sample = {
x: { title: 'my title' },
y: { name: 'my name' },
//
}
let validate = ajv.getSchema('demo')
res = validate(sample)
assert(res)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment