zod validator
This commit is contained in:
parent
6bc88d8c79
commit
5a8aba7f52
|
@ -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")
|
||||
// }
|
Loading…
Reference in New Issue