express-ajv

1.0.3 • Public • Published

express-ajv middleware

Very simple wrapper to use ajv(another json validator) as express' route level middleware. This one allows you to keep validation logic as separate concern. Your controller will be reached only when request data pass tests.

codeship img

Install

npm install --save express-ajv

Usage

//my-validation-schema.js
//first you have to register all yous schemas
 
const expressAjv = require('express-ajv');
const schema = expressAjv.schema;
 
const jsonSchema1 = require('./some-schema1');
const jsonSchema2 = require('./some-schema2');
const customKeyword = require('./some-keyword');
 
schema.addSchema('s1',jsonSchema1);
schema.addSchema('a2',jsonSchema2);
schema.addKeyword('k1',customKeyword);
 
//to prevent raise condition in your routes use this module
module.exports = expressAjv.validatorFactory;

when we have bootstrapped our validation schema then we can aply validators to our routes

const vf = require('./my-validation-schema');
const router = require('express').Router();
 
router.post('/resource1', vf('s1'), (req, res) => {
    
    //this'll be execute only when request pass validation test
});
router.post('/resource2', vf('s2'), ...controller);

Please notice, this middleware does not stop middleware chain, instead of this just passes errors through next callback so if you want to send any feedback to the user you need add error handler. You can use defaultErrorHandler for this;

//app.js
/*
 * your app configuration here
 */
 
app.use(require('express-ajv').defaultErrorHandler);

Package Sidebar

Install

npm i express-ajv

Weekly Downloads

0

Version

1.0.3

License

ISC

Last publish

Collaborators

  • jatzek_at_netgenes