Struggling with integrating Zod and Prisma for validation in my project
In my user.model.ts
file, I have set up Zod validations as follows:
//user.mode.ts file
const userSchema = z.object({
username: z.string({
required_error: "Username field is required",
}),
email: z
.string({
required_error: "Email field is required",
invalid_type_error: "This field must be in email format",
})
.email(),
password: z
.string({
required_error: "Password field is required",
})
.min(6, "Password must be at least 6 characters"),
});
export type UserModel = z.infer<typeof userSchema>;
In my user.service.ts
file, there is a function attempting to utilize the validation logic from user.model.ts
. Unsure if this implementation is correct.
//user.service.ts file
export const createUser = async (
username: string,
email: string,
password: string
) => {
const user: UserModel = await prisma.user.create({
data: {
username: username,
email: email,
password: password,
},
});
return user;
};
The following snippet shows how it appears in the authController.ts
file:
//authController.ts file
export const signUpLogic = async (req: Request, res: Response) => {
const { username, email, password } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 10);
//
createUser(username, email, String(hashedPassword));
//
} catch (err) {
if (err instanceof PrismaClientKnownRequestError) {
if (err.code === "P2002") {
res.json({ message: "email already taken" });
}
}
}
};
However, upon running the code to test the validations, an unexpected Prisma error is thrown in the terminal instead of being handled by the catch
block as intended. The validations also do not seem to be functioning properly, allowing incorrect email formats to pass through.