@rplan/express-schema-validation-middleware
TypeScript icon, indicating that this package has built-in type declarations

1.3.0 • Public • Published

rplan/express-schema-validation-middleware

Build Status npm

Introduction

This module provides a express middleware to validate REST request bodies and parameters against swagger openapi specifications.

Further on it provides functionality to validate REST response bodies against swagger openapi specifications, typically used in rest api tests.

Usage

Usage in express middleware

The following example shows how to automatically validate your request body against the schema specified in docs/private.yaml

import {
  OpenApiValidator,
} from '@rplan/express-schema-validation-middleware'

export async function createRestRoute() {
  const openApiValidator = await OpenApiValidator('docs/private.yaml')
  const validateJSONBody = openApiValidator
    .getBodyValidationMiddleware(['/my-route', 'post'])

  const router = new Router()

  router.post(
    '/my-route',
    validateJSONBody,
    (req, res) => {
      const { myValidateProperties } = req.body
      // ...
    },
  )
  
  return router
}

Usage in REST API tests

async function getResponseValidator(httpStatusCode) {
  const openApiValidator = await OpenApiValidator('docs/private.yaml')
  
  const responseValidator = openApiValidator
      .getResponseValidationEndPoint(['/my-route', 'post'])
      .validator(httpStatusCode)

  return responseValidator
}

// ...

it('should validate response', async () => {
      const response = await request(testHost)
        .post('/my-route')
        .send({ someData: 'values' })
        .expect(HttpStatusCodes.CREATED)

      const validator = await getResponseValidator(HttpStatusCodes.CREATED)
      expect(validator.validate(response), validator.errors).to.equal(true)
})

Upgrade Notice

1.X -> 2.X

The api document should not include the api gateway prefix in the server spec. In this version the api-schema-builder was upgraded and now validates the URL prefix in the server section.

E.g. this is not valid

servers:
  - url: https://api.allex.ai/calendar/v1
    description: |
      Calendar service

it should be like this

servers:
  - url: https://api.allex.ai
    description: |
      Calendar service
      Api gateway prefix: /calendar/v1

Readme

Keywords

none

Package Sidebar

Install

npm i @rplan/express-schema-validation-middleware

Weekly Downloads

42

Version

1.3.0

License

MIT

Unpacked Size

20.1 kB

Total Files

13

Last publish

Collaborators

  • muhammadfaizan
  • siavash.sardari
  • nomanurrehman
  • rplan-ci
  • ady.shehadeh
  • daniel-0815
  • dtimmreck
  • hweber.actano
  • mkronschnabl.actano
  • mpuls
  • dschmidt_actano
  • mnicorici
  • actano-resources-hl
  • wgrall
  • nehap09
  • msagir
  • sevinjguluzade
  • mhnpd
  • tonirucks