@rplan/express-schema-validation-middleware
v1.3.0
Published
rplan/express-schema-validation-middleware ===========================================
Downloads
232
Maintainers
Keywords
Readme
rplan/express-schema-validation-middleware
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