1.2.1 • Published 4 years ago

express-openapi-middleware v1.2.1

Weekly downloads
3
License
MIT
Repository
-
Last release
4 years ago

Inline docs Build Status dependencies Status devDependencies Status

A fairly small library that provides middleware to define and validate routes similarly to express-jsonschema and utility to create OpenAPI 3.0.x compatible "paths" object from those definitions.

Advantages over similar integration tools:

  • Modular - documentaion can be chained and mounted just like regular middleware.
  • Flexible - no need to modify a single single line of existing application logic.
  • No code duplication - validation rules and documentaion are the same thing, right next to actual implementation.
  • No Router or Application modifications needed - it's just a middleware.
  • Small and simple

Limitations:

  • No support for optional and repeated path variables (yet)
  • Documentation generation skips routes that have non-standard path regular expressions (i.e. not compatible to those generated by path-to-regexp).
  • Route middlewares are considered leaves (i.e. routers mounted to Route-s are not scanned).

Note: Documentation objects should generally be immutable.

Usage

import { Router } from 'express';
import { apiOperation, createPaths } from 'express-openapi-middleware';


const router = new Router;

router.get('/pet/:pet', apiOperation({
	tags: [ 'Pet' ],
	summary: 'List pets',
	parameters: [{
		in: 'path',
		name: 'pet',
		description: 'Pet ID',
		required: true,
		schema: {
			type: 'string',
			minLength: 1
		}
	}]
}), (req, res, next) => {
	db.get(req.params.pet)
		.then(pet => {
			res.send(pet);
		}, next)
});


const pathsObject = createPaths(router);

/**
pathsObject =>
  /pet/{pet}:
    get:
      tags:
        - Pet
      summary: 'List pets'
      parameters:
        - in: 'path'
          name: 'pet'
          description: 'Pet ID'
          required: true
          schema:
            type: 'string'
            minLength: 1
*/

How it works

Validation works very similarly to express-jsonschema. To generate the OpenAPI "paths" object, createPaths(router) recursively scans router for Route-s while creating chains of paths and apiOperation middlewares. The "operation" objects attached to these middlewares are then merged together and added to "paths" object.

License

MIT