-
Notifications
You must be signed in to change notification settings - Fork 113
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
For #1, add strict validation of responses.
- Loading branch information
1 parent
1cdeb12
commit f139fd4
Showing
2 changed files
with
41 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters