zod validator

This commit is contained in:
Adria Navarro 2024-10-08 11:41:04 +02:00
parent 6bc88d8c79
commit 5a8aba7f52
1 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,33 @@
import { AnyZodObject } from "zod"
import { Ctx } from "@budibase/types"
function validate(schema: AnyZodObject, property: "body" | "params") {
// Return a Koa middleware function
return (ctx: Ctx, next: any) => {
if (!schema) {
return next()
}
let params = null
if (ctx[property] != null) {
params = ctx[property]
} else if (property === "body" && ctx.request[property] != null) {
params = ctx.request[property]
} else if (ctx.request.get(property) != null) {
params = ctx.request.get(property)
}
const { error } = schema.safeParse(params)
if (error) {
ctx.throw(400, `Invalid ${property} - ${error.message}`)
}
return next()
}
}
export function validateBody(schema: AnyZodObject) {
return validate(schema, "body")
}
// export function validateParams(schema: Joi.Schema) {
// return validate(schema, "params")
// }