This package is used to perform input validation to express app using a Swagger (Open API) definition and ajv
Table of Contents
npm install --save express-ajv-swagger-validation
const swaggerValidator = require('express-ajv-swagger-validation');
This middleware validates the request body, headers, path parameters and query parameters according to the path definition in the swagger file. Please make sure to use this middleware inside a route definition in order to have req.route.path
assign to the most accurate express route.
Init the middleware with the swagger definition.
The function returns a Promise.
PathToSwaggerFile
- Path to the swagger definitionoptions
- Additional options for the middleware
Options currently supported:
-
framework
- Defines in which framework the middleware is working ('koa' or 'express'). As default, set to 'express'. -
formats
- Array of formats that can be added toajv
configuration, each element in the array should includename
andpattern
. -
keywords
- Array of keywords that can be added toajv
configuration, each element in the array can be either an object or a function. If the element is an object, it must includename
anddefinition
. If the element is a function, it should acceptajv
as its first argument and inside the function you need to callajv.addKeyword
to add your custom keyword -
beautifyErrors
- Boolean that indicates if to beautify the errors, in this case it will create a string from the Ajv error.- Examples:
query/limit should be <= 100
- query parampath/petId should NOT be shorter than 3 characters
- path param not in formatbody/[0].test.field1 should be string
- Item in an array bodybody/test should have required property 'field1'
- nested fieldbody should have required property 'name'
- Missing field in body
You can see more examples in the tests
- Examples:
-
firstError
- Boolean that indicates if to return only the first error. -
makeOptionalAttributesNullable
- Boolean that forces preprocessing of Swagger schema to include 'null' as possible type for all non-required properties. Main use-case for this is to ensure correct handling of null values when Ajv type coercion is enabled -
ajvConfigBody
- Object that will be passed as config to new Ajv instance which will be used for validating request body. Can be useful to e. g. enable type coercion (to automatically convert strings to numbers etc). See Ajv documentation for supported values. -
ajvConfigParams
- Object that will be passed as config to new Ajv instance which will be used for validating request body. See Ajv documentation for supported values. -
contentTypeValidation
- Boolean that indicates if to perform content type validation in caseconsume
field is specified and the request body is not empty. -
expectFormFieldsInBody
- Boolean that indicates whether form fields of non-file type that are specified in the schema should be validated against request body (e. g. Multer is copying text form fields to body)
formats: [
{ name: 'double', pattern: /\d+\.(\d+)+/ },
{ name: 'int64', pattern: /^\d{1,19}$/ },
{ name: 'int32', pattern: /^\d{1,10}$/ }
]
swaggerValidator.init('test/unit-tests/input-validation/pet-store-swagger.yaml')
.then(function () {
const app = express();
app.use(bodyParser.json());
app.get('/pets', swaggerValidator.validate, function (req, res, next) {
return res.json({ result: 'OK' });
});
app.post('/pets', swaggerValidator.validate, function (req, res, next) {
return res.json({ result: 'OK' });
});
app.get('/pets/:petId', swaggerValidator.validate, function (req, res, next) {
return res.json({ result: 'OK' });
});
app.use(function (err, req, res) {
if (err instanceof swaggerValidator.InputValidationError) {
return res.status(400).json({ more_info: JSON.stringify(err.errors) });
}
});
const server = app.listen(serverPort, function () {});
});
'use strict';
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const inputValidation = require('../../src/middleware');
let app = new Koa();
let router = new Router();
app.use(bodyParser());
app.use(router.routes());
module.exports = inputValidation.init('test/pet-store-swagger.yaml', {framework: 'koa'})
.then(function () {
router.get('/pets', inputValidation.validate, async function(ctx, next) {
ctx.status = 200;
ctx.body = { result: 'OK' };
});
router.post('/pets', inputValidation.validate, async function (ctx, next) {
ctx.status = 200;
ctx.body = { result: 'OK' };
});
router.get('/pets/:petId', inputValidation.validate, async function (ctx, next) {
ctx.status = 200;
ctx.body = { result: 'OK' };
});
router.put('/pets', inputValidation.validate, async function (ctx, next) {
ctx.status = 200;
ctx.body = { result: 'OK' };
});
return Promise.resolve(app);
});
- Objects - it is important to set any objects with the property
type: object
inside your swagger file, although it isn't a must in the Swagger (OpenAPI) spec in order to validate it accurately with ajv it must be marked asobject
- multipart/form-data (files) supports is based on
express/multer
- koa support - When using this package as middleware for koa, the validations errors are being thrown.
- koa packages - This package supports koa server that uses
koa-router
,koa-bodyparser
andkoa-multer
- supporting inheritance with discriminator , only if the ancestor object is the discriminator.
- The discriminator supports in the inheritance chain stop when getting to a child with no discriminator (a leaf in the inheritance tree), meaning a leaf can't have a field which starts a new inheritance tree. so child with no discriminator cant point to other child with discriminator,
Using mocha, istanbul and mochawesome
npm test