Validate API requests and responses with express-oas-validator
masterYou can use express-oas-validator to ensure incoming requests and outgoing responses match your JSDoc documentation.
Because the validator requires the full Swagger schema, you must wait for the express-jsdoc-swagger instance to finish generating the definition. You can do this by listening to the finish event on the instance.
- Install the validator:
npm install --save express-oas-validator. - Create a wrapper that waits for the
finishevent on theexpressJSDocSwaggerinstance. - Use
validateRequest()as middleware for routes. - Use
validateResponse(message, req)inside route handlers to validate the response body.
const { init } = require('express-oas-validator');
// Helper to wait for swagger definition
const waitForValidator = instance => new Promise((resolve, reject) => {
instance.on('finish', (swaggerDef) => {
const { validateRequest, validateResponse } = init(swaggerDef);
resolve({ validateRequest, validateResponse });
});
instance.on('error', reject);
});
// Usage in server setup
const instance = expressJSDocSwagger(app)(options);
const serverApp = async () => {
const { validateRequest, validateResponse } = await waitForValidator(instance);
/**
* POST /api/v1/songs
* @param {Song} request.body.required - song info
* @return {object} 200 - song response
*/
app.post('/api/v1/songs', validateRequest(), (req, res) => res.send('Saved!'));
/**
* POST /api/v1/name
* @param {string} request.body.required - name
* @return {object} 200 - success
*/
app.post('/api/v1/name', (req, res, next) => {
try {
validateResponse('Error string', req);
return res.send('Hello!');
} catch (error) {
return next(error);
}
});
};