omar-dulaimi / prisma-zod-generator

Prisma 2+ generator to emit Zod schemas from your Prisma schema
MIT License
535 stars 45 forks source link

Pure model schema? #43

Open lilingxi01 opened 1 year ago

lilingxi01 commented 1 year ago

Problem

Does this library generate pure model schema? It should be, for example, the output of findUnique (not the argument of findUnique). I try to find this, but cannot find any file having such thing (probably missed in tons of files).

Suggested solution

Just generate the zod based on the model itself. Similar to the output of zod-prisma.

lilingxi01 commented 1 year ago

It might be similar to what CreateInput schema has right now, but required fields which have default values are actually optional in CreateInput schema.

u007 commented 1 year ago

i saw code generated zod is already contain optional for create. but I find issue with findUnique as well due to "distinct". i think findFirst schema should use original prisma enums, don't need to generate new enum, my fix was:

//....
import { Prisma } from '@prisma/client'

export const TaskFindFirstSchema = z.object({
  select: TaskSelectObjectSchema.optional(),
  include: TaskIncludeObjectSchema.optional(),
  where: TaskWhereInputObjectSchema.optional(),
  orderBy: z
    .union([
      TaskOrderByWithRelationInputObjectSchema,
      TaskOrderByWithRelationInputObjectSchema.array(),
    ])
    .optional(),
  cursor: TaskWhereUniqueInputObjectSchema.optional(),
  take: z.number().optional(),
  skip: z.number().optional(),
  distinct: z.array(z.nativeEnum(Prisma.TaskScalarFieldEnum)).optional(),
})
lilingxi01 commented 1 year ago

I mean a zod object that just contains what prisma model has.

For example,

model ExampleModel {
  id      String      @id @default(uuid())
  name    String?
}

Then what I want is:

z.object({
  id: z.string(),
  name: z.string().optional(),
});

In Create schema, id is optional, which is not an alternative solution my case.

u007 commented 1 year ago

ya i do agree id should be optional for create

here is my create schema, seems to be correct

Screenshot 2022-11-22 at 9 35 30 PM
chrishoermann commented 1 year ago

@lilingxi01 you could try my new generator that I just published zod-prisma-types that lets you just create the zod-schemas for the models as you mentioned. Additionally you can write custom validation logic in prismas rich comments.