我试图使用zod验证器,与typeform。我看到了一些如何使用zod的教程。我写了一点代码,但是,它不起作用,它说&;message&;; &;payloadSchema。safeParse不是一个函数。我正在尝试验证产品存储方法。
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,
});
}
}
};
在payloadSchema
中,body
字段应为z.object。由于您将req.body
放在payloadSchema.safeParse(req.body)中,因此可以从payloadSchema
中删除body字段:
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",
}),
}),
}),
});