Skip to content

Instantly share code, notes, and snippets.

@CacheControl
Last active January 2, 2024 18:48
Show Gist options
  • Save CacheControl/8f6e3db86c65674da6db2a19999993ea to your computer and use it in GitHub Desktop.
Save CacheControl/8f6e3db86c65674da6db2a19999993ea to your computer and use it in GitHub Desktop.
// 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()
})
@NikhilNanjappa-zz
Copy link

NikhilNanjappa-zz commented Oct 10, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment