How does one use prisma enums with zod when creating a new "post".

For eg. A post has tags -> Tag[] enum Tag { "BUSINESS" | "DESIGN"} What is the best way to use the prisma enum with zod. Currently I get this error. import { Tag } from "@prisma/client"; const [tags, setTags] = useState<Tag[]>([]); {Object.values(Tag).map((tag) => { return (...) )}} Type 'Tag[]' is not assignable to type '"BUSINESS" | "DESIGN"'.ts(2322)
7 Replies
thomasmacfarlaine
I have tried this as well: const tags = z.nativeEnum(Tag).array(); type Tags = z.infer<typeof tags>;
JulieCezar
JulieCezar2y ago
Generally I created the zod types myself... Because for the most part I want to display specific error messages or have specific restrictions... E.g. a Post's name is a string, but I also want it to be min 10 characters... So for the most part here you have to create zod types by hand, however, if you match the zod attribute names to the ones in your db you can easily add the whole input into the prisma queries. Something like so:
// In database
model Tag {
id number
name string
}

const zodTags = z.array(z.union([z.literal("BUSINESS"), z.literal("DESIGN")]))

type Tag = z.infer<typeof zodTags>
// In database
model Tag {
id number
name string
}

const zodTags = z.array(z.union([z.literal("BUSINESS"), z.literal("DESIGN")]))

type Tag = z.infer<typeof zodTags>
and now type Tag is "BUSINESS" | "DESIGN"
thomasmacfarlaine
Thanks - ideally I would like to not have to duplicate the types. I am exploring using https://www.npmjs.com/package/zod-prisma
npm
zod-prisma
A Prisma generator that creates Zod schemas for all of your models. Latest version: 0.5.4, last published: a year ago. Start using zod-prisma in your project by running npm i zod-prisma. There are 2 other projects in the npm registry using zod-prisma.
thomasmacfarlaine
However I like your approach as it seems straight forward. I am sure there is a neat way to do it.
JulieCezar
JulieCezar2y ago
Thant would be nice, but you can't have it all xD Good luck, but be careful with that, it was last updated 1 year ago, and who knows what may not work anymore You could write it out yourself if you have a simpler schema
thomasmacfarlaine
Yes, it's not the best
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server