chrishoermann / zod-prisma-types

Generator creates zod types for your prisma models with advanced validation
Other
578 stars 43 forks source link

[BUG] Optional fields is being generated as nullable #228

Open vidz1979 opened 6 months ago

vidz1979 commented 6 months ago

Describe the bug

My Prisma model is like this:

model Entity {
  id        String   @id @default(cuid())
  field String?
  fieldWorkaround              String? /// @zod.custom.use(z.string().optional())
}

My generated Zod type is like that:

export const EntitySchema = z.object({
  id: z.string().cuid(),
  field: z.string().nullable(),
  fieldWorkaround: z.string().optional().nullable(),
})

It's worth nothing that "String?" is producing a nullable field, which produces a required validation in forms. I need an optional field, which I achieved using a custom modifier.

Package versions (please complete the following information): "zod": "^3.22.4", "zod-prisma-types": "^3.1.6"

chrishoermann commented 6 months ago

@vidz1979 maybe you can try the option writeNullishInModelTypes this would result in a schema like

export const EntitySchema = z.object({
  id: z.string().cuid(),
  field: z.string().nullish(), // null or undefined
  fieldWorkaround: z.string().optional().nullish(), //null or undefined
})