2020-09-10 18:46:34 +02:00
|
|
|
function validate(schema, property) {
|
|
|
|
// Return a Koa middleware function
|
|
|
|
return (ctx, next) => {
|
2020-09-22 00:19:45 +02:00
|
|
|
if (!schema) {
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
let params = null
|
|
|
|
if (ctx[property] != null) {
|
|
|
|
params = ctx[property]
|
|
|
|
} else if (ctx.request[property] != null) {
|
|
|
|
params = ctx.request[property]
|
|
|
|
}
|
|
|
|
const { error } = schema.validate(params)
|
|
|
|
if (error) {
|
|
|
|
ctx.throw(400, `Invalid ${property} - ${error.message}`)
|
|
|
|
return
|
2020-09-10 18:46:34 +02:00
|
|
|
}
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-04 12:32:22 +02:00
|
|
|
module.exports.body = schema => {
|
2020-09-10 18:46:34 +02:00
|
|
|
return validate(schema, "body")
|
|
|
|
}
|
2021-02-08 18:22:07 +01:00
|
|
|
|
2021-05-04 12:32:22 +02:00
|
|
|
module.exports.params = schema => {
|
2021-02-08 18:22:07 +01:00
|
|
|
return validate(schema, "params")
|
|
|
|
}
|