Created
May 19, 2022 13:53
-
-
Save fed135/7a45eab6510a78a5d514fae9a5cb6734 to your computer and use it in GitHub Desktop.
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
// This middleware example takes in the entire swagger spec and tries to find the route in it. | |
const validate = require('swagger-route-validator'); | |
const spec = require('./my-spec'); | |
function validateRequest(req, res, next) { | |
const layer = app._router.stack.find(bloc => bloc.route && bloc.regexp.exec(req.originalUrl) !== null); | |
// Check if route exists | |
if (!layer) return next(); | |
// prevents routing from running twice: | |
req.route = layer.route; | |
function extractPathParams(url, layer) { | |
const parameters = {}; | |
if (layer.keys.length > 0) { | |
const cleanedInbound = url.split('/'); | |
const cleanedOriginal = layer.route.path.split('/'); | |
let keysIndex = 0; | |
for (let i = 0; i < cleanedInbound.length; i++) { | |
if (!layer.keys[keysIndex]) continue; | |
if (cleanedInbound[i] !== cleanedOriginal[i]) { | |
parameters[layer.keys[keysIndex].name] = cleanedInbound[i]; | |
keysIndex++; | |
} | |
} | |
} | |
return parameters; | |
} | |
const matchingSpec = spec[layer.route.path] && spec[layer.route.path][req.method.toLowerCase()]; | |
// Path not in specs | |
if (!matchingSpec) return next(); | |
Object.assign(req.params, extractPathParams(req.originalUrl, layer)); | |
// Check validation errors | |
const errors = validate(matchingSpec, req); | |
if (errors.length > 0) return res.status(400).json(errors); | |
next(); | |
} | |
module.exports = validateRequest; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment