1
0
Fork 0
mirror of synced 2024-06-29 19:41:03 +12:00
budibase/packages/backend-core/src/middleware/joi-validator.js

29 lines
637 B
JavaScript
Raw Normal View History

2022-07-22 22:50:51 +12:00
function validate(schema, property) {
// Return a Koa middleware function
return (ctx, next) => {
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
}
return next()
}
}
module.exports.body = schema => {
return validate(schema, "body")
}
module.exports.params = schema => {
return validate(schema, "params")
}