chrishoermann / zod-prisma-types

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

[BUG] Nested types does not get generated when using the createRelationValuesTypes option together with Prisma composite types #254

Open DeRp-DaWg opened 6 months ago

DeRp-DaWg commented 6 months ago

When using the option createRelationValuesTypes, together with Prisma composite types (currently only available when using the MongoDB provider), the generated WithRelations zod schemas and types, does not use the other generated WithRelations zod schemas and types. In other words, nested composite types does not work.

(Sorry for that terrible and confusing explanation.)

Here's an example in the README.md demonstrating my expectations: https://github.com/chrishoermann/zod-prisma-types#createrelationvaluestypes And another relevant issue: #54

I've also created a simple example, to further demonstrate my issue.

Example Prisma Schema

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator zod {
  provider                  = "zod-prisma-types"
  createRelationValuesTypes = true
}

model User {
  id             String         @id @default(auto()) @map("_id") @db.ObjectId
  createdAt      DateTime       @default(now())
  name           String?
  contactDetails ContactDetails
  posts          Post[]
}

type ContactDetails {
  email String
  phone String
}

model Post {
  id        String    @id @default(auto()) @map("_id") @db.ObjectId
  createdAt DateTime  @default(now())
  published Boolean   @default(false)
  title     String
  authorId  String    @db.ObjectId

  User   User?   @relation(fields: [userId], references: [id])
  userId String? @db.ObjectId
}

Expected output

export type UserRelations = {
  contactDetails: ContactDetails;
  posts: PostWithRelations[];
};

export type UserWithRelations = z.infer<typeof UserSchema> & UserRelations

export const UserWithRelationsSchema: z.ZodType<UserWithRelations> = UserSchema.merge(z.object({
  contactDetails: z.lazy(() => ContactDetailsSchema),
  posts: z.lazy(() => PostWithRelationsSchema).array(),
}))

Resulting output

export type UserRelations = {
  contactDetails: ContactDetails;
  posts: Post[];
};

export type UserWithRelations = z.infer<typeof UserSchema> & UserRelations

export const UserWithRelationsSchema: z.ZodType<UserWithRelations> = UserSchema.merge(z.object({
  contactDetails: z.lazy(() => ContactDetailsSchema),
  posts: z.lazy(() => PostSchema).array(),
}))

Package versions: