You are forgotting to use await inside signUpLogic.
And the validations are not working. I still can enter the wrong email format into the email field.
You are not using zod to parse the data.
You can do the following:
export const createUser = async ({
username,
email,
password,
}: UserModel) => {
const user: UserModel = await prisma.user.create({
data: {
username,
email,
password,
},
});
return user;
};
export const signUpLogic = async (req: Request, res: Response) => {
const { username, email, password } = req.body;
try {
const hashedPassword = await bcrypt.hash(password, 10);
const result = userSchema.safeParse({ username, email, password: String(hashedPassword)});
if(result.success) {
await createUser(result.data);
} else {
// handle wrong parsing result
}
} catch (err) {
if (err instanceof PrismaClientKnownRequestError) {
if (err.code === "P2002") {
res.json({ message: "email already taken" });
}
}
}
};
Answer from Nullndr on Stack OverflowZod validator using Prisma (MySQL) enum
Which source of truth in a TS/Zod/Prisma project?
A dream stack suggestions
How to best design my schema in postgres when using zod and typescript?
» npm install zod-prisma-types
Hi,
I'm trying to make a zod validator, it should parse data coming from frontend form (im using next.js app router)
here are code snippets:
schema.prisma:
model ProposalOption {
id Int @id @default(autoincrement())
name String @db.TinyText
category OptionCategory
active Boolean
}
enum OptionCategory {
reason
size
feature
additional
}now based off that schema i would like to create a zod validator, but idk how to define that...
import z from "zod";
import type { OptionCategory } from "@prisma/client";
const options: OptionCategory[] = ["additional", "feature", "reason", "size"];
export const CreateProposalOptionValidator = z.object({
description: z
.string()
.min(5, { message: "Description must have at least 5 characters" })
.max(100, { message: "Description must have less than 100 characters" }),
// @ts-expect-error TODO: fix this
category: z.enum(options),
});
export type ProposalOptionCreateRequest = z.infer<
typeof CreateProposalOptionValidator
>;unfortunately category key is atm just a string, not a OptionCategory, therefore on the backend i have a type error
const body = await req.json();
const { category, description } = CreateProposalOptionValidator.parse(body);
await db.proposalOption.create({
data: {
// @ts-expect-error
category,
description,
},
});
Any hints?
Thanks in advance!!
I have a Typescript project and want to use form validation with Zod on the front end. I’m also using Prisma ORM. The issue is I’m struggling to get one source of truth for the resource being created/updated. How do you keep those in sync? At the moment, I have 3 separate schemas. What’s the best practice to define your schema once and keep TS, DB and frontend validation in sync?
» npm install prisma-zod-generator