1
0
Fork 0
mirror of synced 2024-06-30 20:10:54 +12:00
budibase/packages/server/src/middleware/joi-validator.ts

40 lines
887 B
TypeScript
Raw Normal View History

const Joi = require("joi")
function validate(schema, property) {
// Return a Koa middleware function
return (ctx, next) => {
2020-09-22 10:19:45 +12: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]
}
// not all schemas have the append property e.g. array schemas
if (schema.append) {
schema = schema.append({
createdAt: Joi.any().optional(),
updatedAt: Joi.any().optional(),
})
}
2020-09-22 10:19:45 +12:00
const { error } = schema.validate(params)
if (error) {
ctx.throw(400, `Invalid ${property} - ${error.message}`)
return
}
return next()
}
}
2021-05-04 22:32:22 +12:00
module.exports.body = schema => {
return validate(schema, "body")
}
2021-05-04 22:32:22 +12:00
module.exports.params = schema => {
return validate(schema, "params")
}