UNPKG

bs-ajv

Version:

BucklesScript bindings to Ajv (Another JSON Validator)

79 lines (75 loc) 2.46 kB
const Ajv = require('./src/Ajv.bs'); const invalidData = { "messages": { "Dr. Beverly Crusher": "How are you feeling!", "Cpt. Jean-Luc Picard": "No children allowed on the bridge?", "Lt. Cmdr. Data": "I am an android!", "Act. Ens. Wesley Crusher": "Hi, I'm Wesley!" }}; const schema = { "title": "Message", "type": "object", "properties": { "messages": { "type": "object", "maxProperties": 3, "minProperties": 1, "additionalProperties": false, "patternProperties": { "Dr\\. .*": { "type": "string", "pattern": "^.*\\?$" }, "Cpt\\. .*": { "type": "string", "pattern": "^.*!$" }, "Lt. Cmdr. .*": { "type": "string", "pattern": "^.*[\.?]$" }, "Act. Ens. .*": { "type": "string", "pattern": "^$" } } } }, "required": [ "messages" ] }; /* Using bs-ajv from Javascript. TODO is this interface too complicated? */ /* Define async validator for custom keyword */ /* TODO what argument is _ ? */ function asyncValidator(schema, data, _) { console.log('asyncValidator got schema=', schema); console.log('asyncValidator got data=', data); /* Mock request latency */ return new Promise((resolve, reject) => { setTimeout(() => { resolve(true); }, 1000); }) } /* Instantiate an Ajv.Options.t -- just an empty JS object */ const ajvOptions = new Ajv.makeOptions(); console.log('ajvOptions=', typeof ajvOptions); /* Instantiate validator factory */ /* TODO does this just create an empty object with Object.prototype prototype? */ const ajv = Ajv.makeAjv(ajvOptions); console.log('ajv=', typeof ajv); /* Instantiate custom validation keyword */ /* TODO does this just create an empty object with Object.prototype prototype? */ const keyword = Ajv.makeKeyword(); console.log('keyword constructor name=', keyword.constructor.name); console.log('keyword prototype is Object.prototype=', keyword.__proto__ === Object.prototype); /* Set asynchronous validator for custom keyword */ Ajv.setAsyncValidator(keyword, asyncValidator); /* Instantiate synchronous validator */ const validator = Ajv.compileSync(schema, ajv); console.log('validator=', typeof validator); /* Evalutae example document against synchronous validator */ const result = validator(invalidData); console.log('result=', result); /* goodbye.wav */ console.log('normal exit');