I'm trying to use zod validator, with typeorm. I saw few tutorials how to use zod. and i write little code but, it does not work it's saying "message": "payloadSchema.safeParse is not a function". am trying to validate product store method.
export const createProduct = async (req: Request, res: Response) => {
try {
const payloadSchema = {
body: z.object({
price: z.number({
required_error: "price is required",
}),
image: z.string({
required_error: "image is required",
}),
translations: z.object({
ge: z.object({
title: z.string({
required_error: "title is required",
}),
description: z.string({
required_error: "description is required",
}),
}),
en: z.object({
title: z.string({
required_error: "title is required",
}),
description: z.string({
required_error: "description is required",
}),
}),
}),
}),
};
type Payload = z.infer<typeof payloadSchema>;
const parsedData = payloadSchema.safeParse(req.body);
if (!parsedData.success) {
res.status(400).send({
error: parsedData.error,
});
return;
}
const { image, price, translations } = req.body;
const product = new Product();
product.image = parsedData.image;
product.price = parsedData.price;
product.translations = parsedData.translations;
await product.save();
return res.json(product);
} catch (e) {
if (e instanceof Error) {
return res.status(400).json({
message: e.message,
});
}
}
};
In the payloadSchema
the body
field should be z.object. Since you put the req.body
to the payloadSchema.safeParse(req.body), the body field can be removed from the payloadSchema
:
const payloadSchema = z.object({
price: z.number({
required_error: "price bitch!",
}),
image: z.string({
required_error: "image required",
}),
translations: z.object({
ge: z.object({
title: z.string({
required_error: "title is required",
}),
description: z.string({
required_error: "description is required",
}),
}),
en: z.object({
title: z.string({
required_error: "title is required",
}),
description: z.string({
required_error: "description is required",
}),
}),
}),
});