ajv.addKeyword({
keyword: "range",
type: "number",
macro: ([minimum, maximum]) => ({minimum, maximum}), // schema with keywords minimum and maximum
// metaSchema: the same as in the example above
})
ajv.addKeyword({
keyword: "range",
type: "number",
compile([min, max], parentSchema) {
return parentSchema.exclusiveRange === true
? (data) => data > min && data < max
: (data) => data >= min && data <= max
},
errors: false,
metaSchema: {
// schema to validate keyword value
type: "array",
items: [{type: "number"}, {type: "number"}],
minItems: 2,
additionalItems: false,
},
})
const schema = {
range: [2, 4],
exclusiveRange: true,
}
const validate = ajv.compile(schema)
console.log(validate(2.01)) // true
console.log(validate(3.99)) // true
console.log(validate(2)) // false
console.log(validate(4)) // false
//...
const conf = require('../conf');
const ajv = new Ajv({
schemaId: 'auto',
allErrors: true,
verbose: true,
});
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
function URIfromId(id) {
return url.parse(id).path;
}
//...
import {_, nil, KeywordCxt} from Ajv
ajv.addKeyword({
keyword: "range",
type: "number",
code(cxt: KeywordCxt) {
const {schema, parentSchema, data} = cxt
const [min, max] = schema
const eq: Code = parentSchema.exclusiveRange ? _`=` : nil
cxt.fail(_`${data} <${eq} ${min} || ${data} >${eq} ${max}`)
},
metaSchema: {
type: "array",
items: [{type: "number"}, {type: "number"}],
minItems: 2,
additionalItems: false,
},
})
const ajv = new Ajv()
ajv.addKeyword({
keyword: "idExists",
async: true,
type: "number",
validate: checkIdExists,
})
async function checkIdExists(schema, data) {
// this is just an example, you would want to avoid SQL injection in your code
const rows = await sql(`SELECT id FROM ${schema.table} WHERE id = ${data}`)
return !!rows.length // true if record is found
}
const schema = {
$async: true,
properties: {
userId: {
type: "integer",
idExists: {table: "users"},
},
postId: {
type: "integer",
idExists: {table: "posts"},
},
},
}
const validate = ajv.compile(schema)
validate({userId: 1, postId: 19})
.then(function (data) {
console.log("Data is valid", data) // { userId: 1, postId: 19 }
})
.catch(function (err) {
if (!(err instanceof Ajv.ValidationError)) throw err
// data is invalid
console.log("Validation errors:", err.errors)
})