Skip to content

igor-savin-ht/express-ajv-swagger-validation

 
 

Repository files navigation

express-ajv-swagger-validation

NPM

NPM

NPM Version NPM Downloads Build Status Test Coverage NSP Status MIT License

This package is used to perform input validation to express app using a Swagger (Open API) definition and ajv

Table of Contents

Install

npm install --save express-ajv-swagger-validation

API

How to use

var swaggerValidator = require('express-ajv-swagger-validation');

express-ajv-swagger-validation.validate

This Middleware validate 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 route definition in order to have req.route.path assign to the most accurate express route.

express-ajv-swagger-validation.init(PathToSwaggerFile, options)

Init the middleware with the swagger definition.

The function return Promise.

Arguments

  • PathToSwaggerFile – Path to the swagger definition
  • options – Additional options for the middleware.
Options

Options currently supports:

  • formats - Array of formats that can be added to ajv configuration, each element in the array should include name and pattern.

  • 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 param
      • path/petId should NOT be shorter than 3 characters - path param not in format
      • body/[0].test.field1 should be string - Item in an array body
      • body/test should have required property 'field1' - nested field
      • body should have required property 'name' - Missing field in body

    You can see more examples in the tests

  • firstError - Boolean that indicates if to return only the first error.

formats: [
    { name: 'double', pattern: /\d+\.(\d+)+/ },
    { name: 'int64', pattern: /^\d{1,19}$/ },
    { name: 'int32', pattern: /^\d{1,10}$/ }
]

Usage Example

swaggerValidator.init('test/unit-tests/input-validation/pet-store-swagger.yaml')
    .then(function () {
        var app = express();
        app.use(bodyParser.json());
        app.get('/pets', swaggerValidator.validate, function (req, res, next) {
            res.json({ result: 'OK' });
        });
        app.post('/pets', swaggerValidator.validate, function (req, res, next) {
            res.json({ result: 'OK' });
        });
        app.get('/pets/:petId', swaggerValidator.validate, function (req, res, next) {
            res.json({ result: 'OK' });
        });

        app.use(function (err, req, res, next) {
            if (err instanceof swaggerValidator.InputValidationError) {
                res.status(400).json({ more_info: JSON.stringify(err.errors) });
            }
        });

        var server = app.listen(serverPort, function () {
        });
    });

Important Notes

  • 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 as object
  • multipart/form-data (files) supports is based on express/multer

Running Tests

Using mocha, istanbul and mochawesome

npm test

About

Input validation using Swagger (Open API) and ajv

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%