Last active
January 2, 2024 18:48
-
-
Save CacheControl/8f6e3db86c65674da6db2a19999993ea 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
// there are many json-schema validators available, I prefer ajv | |
let Ajv = require('ajv') | |
let ajv = Ajv({ allErrors:true }) | |
let swagger = require('./docs/my-swagger-definition') | |
// validation middleware | |
let validateSchema = (parameters) => { | |
return (req, res, next) => { | |
let errors = [] | |
parameters.map(param => { | |
let valid = ajv.validate(parameters[param].schema, req.body[param]) | |
if (!valid) { | |
errors.push(ajv.errors) | |
} | |
}) | |
if (errors.length) return res.send(errors) | |
next() | |
} | |
} | |
app.post('/pets', validateSchema(swagger.paths['/pets'].post.parameters), (req, res) => { | |
// parameters are valid; code can interact with database | |
// ! you must still protect from SQL injection ! | |
res.send(req.body).status(201).end() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if I want to write this middleware for all the routes. How would it work for a route like
/pets/{petId}
?The incoming request would have a value in place of
petId
eg./pets/12
which would not match any paths from swagger file.