2020-09-10 18:46:34 +02:00
|
|
|
function validate(schema, property) {
|
|
|
|
// Return a Koa middleware function
|
|
|
|
return (ctx, next) => {
|
|
|
|
if (schema) {
|
2020-09-16 20:25:52 +02:00
|
|
|
let params =
|
|
|
|
ctx[property] != null
|
|
|
|
? ctx[property]
|
|
|
|
: ctx.request[property] != null
|
|
|
|
? ctx.request[property]
|
|
|
|
: null
|
|
|
|
const { error } = schema.validate(params)
|
2020-09-10 18:46:34 +02:00
|
|
|
if (error) {
|
|
|
|
ctx.throw(400, `Invalid ${property} - ${error.message}`)
|
2020-09-16 20:25:52 +02:00
|
|
|
return
|
2020-09-10 18:46:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports.body = schema => {
|
|
|
|
return validate(schema, "body")
|
|
|
|
}
|