Files
medusa-store/packages/medusa/src/api/utils/validate-body.ts
Harminder Virk 9cf0df53b5 feature: add telemetry to the HTTP layer (#9116)
---------

Co-authored-by: adrien2p <adrien.deperetti@gmail.com>
2024-09-13 12:36:54 +05:30

37 lines
925 B
TypeScript

import { NextFunction } from "express"
import { z } from "zod"
import { MedusaRequest, MedusaResponse } from "../../types/routing"
import { zodValidator } from "./zod-helper"
export function validateAndTransformBody(
zodSchema:
| z.ZodObject<any, any>
| ((
customSchema?: z.ZodObject<any, any>
) => z.ZodObject<any, any> | z.ZodEffects<any, any>)
): (
req: MedusaRequest,
res: MedusaResponse,
next: NextFunction
) => Promise<void> {
return async function validateBody(
req: MedusaRequest,
_: MedusaResponse,
next: NextFunction
) {
try {
let schema: z.ZodObject<any, any> | z.ZodEffects<any, any>
if (typeof zodSchema === "function") {
schema = zodSchema(req.additionalDataValidator)
} else {
schema = zodSchema
}
req.validatedBody = await zodValidator(schema, req.body)
next()
} catch (e) {
next(e)
}
}
}