Skip to content

Instantly share code, notes, and snippets.

@fed135
Created May 19, 2022 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fed135/7a45eab6510a78a5d514fae9a5cb6734 to your computer and use it in GitHub Desktop.
Save fed135/7a45eab6510a78a5d514fae9a5cb6734 to your computer and use it in GitHub Desktop.
// 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