chrishoermann / zod-prisma-types

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

Matching nullish fields in comparison to Prisma type #65

Closed pedropmedina closed 1 year ago

pedropmedina commented 1 year ago

Shouldn't the optional fields map exactly to the generated Prisma type. Prisma types generates optional fields as {type} | null, yet the generated zod schema uses nullish which translates to {type} | undefined | null. This tends to cause issues when using the generated types interchangeably with an API's return value (Prisma type).

For example let's say I have a form with a field that expects a type Customer. I will use the generated Zod schema CustomerSchema here and preset the form values upon fetching that customer's data. This is the usual when handling /customer/[id]/update/. The problem here is that Typescript starts complaining as the types received from the API don't match those generated by Zod.

Take for example the following model customer

Generated Prisma type

export type Customer = {
  alcoholRecipientType: string | null
  altName: string | null
  balanceSearch: number | null
  companyName: string | null
  contactList: string | null
  creditHoldOverride: string | null
  currency: number | null
 ...

Generated Zod schema:

export const CustomerSchema = z.object({
  alcoholRecipientType: z.string().nullish(),
  altName: z.string().nullish(),
  balanceSearch: z.number().nullish(),
  companyName: z.string().nullish(),
  contactList: z.string().nullish(),
  creditHoldOverride: z.string().nullish(),
  currency: z.number().nullish(),
...
chrishoermann commented 1 year ago

@pedropmedina you're right. I actually can't remember why I chose nullish over nullable. I'll change it in the next release. Do you think it would make sense to make a generator option for this case?

pedropmedina commented 1 year ago

Hi @chrishoermann. Perhaps there may be a use case for so having the option. However, the whole null vs undefined topic seems very suggestive in javascript and since we're dealing mainly with Prisma and APIs if we want to purposely send no value we send null

I guess having the option won't hurt and will provide backward compatibility??? - My thoughts

chrishoermann commented 1 year ago

if we want to purposely send no value we send null.

Good point. I'll set .nullable() to be the default option and add a generator option to change back to .nullish()

chrishoermann commented 1 year ago

@pedropmedina you can use it now in version 2.0.0-beta.4

pedropmedina commented 1 year ago

Nice. Thank you @chrishoermann