const Ajv = require('ajv');
const ajv = new Ajv({allErrors: true});
ajv.addKeyword({
keyword: "range",
type: "number",
compile([min, max], parentSchema) {
return (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 = {
$id: '/our/schema',
type: "object",
properties: {
foo: {
type: "number",
range: [6, 1]
},
bar: {
type: "number",
range: [1, 5],
}
},
required: ["foo"],
additionalProperties: false
}
const run = () => {
try {
ajv.compile(schema)
} catch (error) {
console.error("Ajv schema is invalid", error);
} finally {
ajv.removeSchema(schema.$id)
}
console.log(ajv.validate(schema, { foo: 7, bar: 2 }));
console.log(ajv.validate(schema, { foo: 1, bar: 4 }));
console.log(Math.ceil(process.memoryUsage().heapUsed / 1024) + "KB")
}
for(let i=0; i < 10; i++) {
run();
}