chrishoermann / zod-prisma-types

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

How to tell zod generator that autogenerated id fields shouldn't be included for safeParsing #162

Closed FaresKi closed 11 months ago

FaresKi commented 11 months ago

Hi! Great plugin, super handful. I just got a quick question. I got a schema model similar to the following:

model Users {
  id        Int        @id @default(autoincrement())
  firstName String     @db.VarChar(50)
  lastName  String     @db.VarChar(50)
  email     String     @unique @db.VarChar(100)
   ...
}

The plugin generates the zod schema, which is helpful:

export const UsersSchema = z.object({
    id: z.number().int(),
    firstName: z.string(),
    lastName: z.string(),
    email: z.string(),
         ...
})

But I want id to be considered optional, so when it comes to creating users, i don't need it to be there. How can I do so?

Thanks!

CyanoFresh commented 11 months ago

you can use

UsersSchema.omit({ id:true })

or

UsersSchema.extend({
   id: z.number().nullish()
})
creising commented 11 months ago

I ran into the same issue and used the omit annotation which removed it from the schema entirely. Alternatively, you can have fields with default values marked as optional by enabling this feature.