diff --git a/packages/server/src/middleware/zod-validator.ts b/packages/server/src/middleware/zod-validator.ts new file mode 100644 index 0000000000..6fb338e5e8 --- /dev/null +++ b/packages/server/src/middleware/zod-validator.ts @@ -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") +// }