Ajv - Asynchronous validation

node v0.12.18
version: 1.0.0
endpointsharetweet
var Ajv = require('ajv'); var ajv = Ajv({allErrors: true}); var request = require("request"); ajv.addFormat('twitter', { async: true, validate: (userName) => new Promise((resolve, reject) => { request.get('https://twitter.com/' + userName, (err, res) => { if (err) reject(err); else resolve(res.statusCode == 200) }); }) }); var schema = { "$async": true, "properties": { "twitter_username": { "type": "string", "format": "twitter" } } }; var validate = ajv.compile(schema); test({twitter_username: 'epoberezkin'}) .then(() => { test({twitter_username: 'no_such_user_name'}) }); function test(data) { return validate(data) .then(() => console.log('valid data: ' + JSON.stringify(data))) .catch((err) => { if (err instanceof Ajv.ValidationError) console.log('invalid data: ' + JSON.stringify(data), 'errors:', err.errors); else console.log(err); }); }
Loading…

no comments

    sign in to comment