chrishoermann / zod-prisma-types

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

Make array fields optional #128

Closed MichaelOren closed 1 year ago

MichaelOren commented 1 year ago

Arrays can be zero or many. In the zero case, they should be optional as this is how prisma behaves on input, I don't need to specify array values.

Not sure if this is the best way to go about this though.

EG:

model AdditionalInfoDetailed {
  id                           String                         @unique @default(cuid())
  BankingProductDetailed       BankingProductDetailed         @relation(fields: [productId], references: [id], onDelete: Cascade)
  productId                    String                         @unique /// @zod.custom.omit([model, input])
  overviewUri                  String?
  termsUri                     String?
  eligibilityUri               String?
  feesAndPricingUri            String?
  bundleUri                    String?
  AdditionalOverviewUris       AdditionalOverviewUris[]
  AdditionalTermsUris          AdditionalTermsUris[]
  AdditionalEligibilityUris    AdditionalEligibilityUris[]
  AdditionalFeesAndPricingUris AdditionalFeesAndPricingUris[]
  AdditionalBundleUris         AdditionalBundleUris[]

  @@index([productId])
}

Makes the following:

export const AdditionalInfoDetailedOptionalDefaultsWithRelationsSchema: z.ZodType<AdditionalInfoDetailedOptionalDefaultsWithRelations> = AdditionalInfoDetailedOptionalDefaultsSchema.merge(z.object({
  BankingProductDetailed: z.lazy(() => BankingProductDetailedOptionalDefaultsWithRelationsSchema),
  AdditionalOverviewUris: z.lazy(() => AdditionalOverviewUrisOptionalDefaultsWithRelationsSchema).array(),
  AdditionalTermsUris: z.lazy(() => AdditionalTermsUrisOptionalDefaultsWithRelationsSchema).array(),
  AdditionalEligibilityUris: z.lazy(() => AdditionalEligibilityUrisOptionalDefaultsWithRelationsSchema).array(),
  AdditionalFeesAndPricingUris: z.lazy(() => AdditionalFeesAndPricingUrisOptionalDefaultsWithRelationsSchema).array(),
  AdditionalBundleUris: z.lazy(() => AdditionalBundleUrisOptionalDefaultsWithRelationsSchema).array(),
}))

Since the arrays can be empty, I want them to be .optional().

I am using these Schemas to parse API responses that I am then putting into prisma.create, which does force me to input the array values.

This may not be right, so happy to discuss or if there is a better way would love some pointers 🙏 😄

I am using partials in the meantime, which may be the better way to go

MichaelOren commented 1 year ago

I think I am doing square peg round hole sort of thing, I should really be using the output to make the right type that I want

I am starting to use the InputSchemas instead

Closing this PR