Skip to content

Commit

Permalink
For #1, add strict validation of responses.
Browse files Browse the repository at this point in the history
  • Loading branch information
jfinkhaeuser committed Feb 12, 2019
1 parent 1cdeb12 commit f139fd4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
36 changes: 36 additions & 0 deletions lib/middleware/validate_responses.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

// Function taken directly from https://github.com/kogosoftwarellc/open-api/tree/master/packages/express-openapi
module.exports = function (req, res, next)
{
const strictValidation = req.apiDoc['x-express-openapi-validation-strict'] ? true : false;
if (typeof res.validateResponse === 'function') {
const send = res.send;
res.send = function expressOpenAPISend(...args) {
const onlyWarn = !strictValidation;
if (res.get('x-express-openapi-validation-error-for') !== undefined) {
return send.apply(res, args);
}
const body = args[0];
let validation = res.validateResponse(res.statusCode, body);
let validationMessage;
if (validation === undefined) {
validation = { message: undefined, errors: undefined };
}
if (validation.errors) {
const errorList = Array.from(validation.errors).map(_ => _.message).join(',');
validationMessage = `Invalid response for status code ${res.statusCode}: ${errorList}`;
console.warn(validationMessage);
// Set to avoid a loop, and to provide the original status code
res.set('x-express-openapi-validation-error-for', res.statusCode.toString());
}
if (onlyWarn || !validation.errors) {
return send.apply(res, args);
} else {
res.status(500);
return res.json({ error: validationMessage });
}
}
}
next();
}
6 changes: 5 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const yaml = require('js-yaml');
const fs = require('fs');
const path = require('path');

const validateResponses = require('./lib/middleware/validate_responses');

// Configure app
const app = express();
app.use(cors());
Expand All @@ -19,7 +21,9 @@ openapi.initialize({
apiDoc: yaml.safeLoad(fs.readFileSync('./api-base.yml')),
app: app,
paths: path.resolve(__dirname, 'paths'),
docsPath: '/swagger.json'
docsPath: '/swagger.json',
'x-express-openapi-additional-middleware': [validateResponses],
'x-express-openapi-validation-strict': true
});

app.use(function(err, req, res, next) {
Expand Down

0 comments on commit f139fd4

Please sign in to comment.