2022-11-16 18:24:13 +01:00
|
|
|
import Joi from "joi"
|
|
|
|
import { BBContext } from "@budibase/types"
|
2022-06-14 13:34:15 +02:00
|
|
|
|
2022-11-16 18:24:13 +01:00
|
|
|
function validate(schema: Joi.Schema, property: string) {
|
2020-09-10 18:46:34 +02:00
|
|
|
// Return a Koa middleware function
|
2022-11-16 18:24:13 +01:00
|
|
|
return (ctx: BBContext, next: any) => {
|
2020-09-22 00:19:45 +02:00
|
|
|
if (!schema) {
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
let params = null
|
|
|
|
if (ctx[property] != null) {
|
|
|
|
params = ctx[property]
|
2022-11-16 18:24:13 +01:00
|
|
|
} else if (ctx.request.get(property) != null) {
|
|
|
|
params = ctx.request.get(property)
|
2020-09-22 00:19:45 +02:00
|
|
|
}
|
2022-06-14 13:34:15 +02:00
|
|
|
|
2022-08-31 13:24:12 +02:00
|
|
|
// not all schemas have the append property e.g. array schemas
|
2022-11-16 18:24:13 +01:00
|
|
|
if ("append" in schema && schema.append) {
|
2022-08-31 13:24:12 +02:00
|
|
|
schema = schema.append({
|
|
|
|
createdAt: Joi.any().optional(),
|
|
|
|
updatedAt: Joi.any().optional(),
|
|
|
|
})
|
|
|
|
}
|
2022-06-14 13:34:15 +02:00
|
|
|
|
2020-09-22 00:19:45 +02:00
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-16 18:24:13 +01:00
|
|
|
export function body(schema: Joi.Schema) {
|
2020-09-10 18:46:34 +02:00
|
|
|
return validate(schema, "body")
|
|
|
|
}
|
2021-02-08 18:22:07 +01:00
|
|
|
|
2022-11-16 18:24:13 +01:00
|
|
|
export function params(schema: Joi.Schema) {
|
2021-02-08 18:22:07 +01:00
|
|
|
return validate(schema, "params")
|
|
|
|
}
|