omar-dulaimi / prisma-trpc-generator

Prisma 2+ generator to emit fully implemented tRPC routers
MIT License
675 stars 34 forks source link

Extend zod schema with prisma.schema comments #14

Open olehmelnyk opened 2 years ago

olehmelnyk commented 2 years ago

Problem

Since Prisma does not have such a reach check as Zod has - like min/max/length, email/URL, transform, etc. - we could add those extra Zod checks using Prisma comments ///

prisma.schema

model Post {
  id String @id @default(uuid()) /// @zod.uuid()

  /// @zod.max(255, { message: "The title must be shorter than 256 characters" })
  title String

  contents String /// @zod.max(10240)
}

zod schema output

export const PostModel = z.object({
    id: z.string().uuid(),
    title: z.string().max(255, { message: 'The title must be shorter than 256 characters' }),
    contents: z.string().max(10240),
})

Suggested solution

here's an example in a similar prisma2zod generator

Just a suggestions

Maybe you can optionally provide an npm package, that generates tRPC based on zod schema from another plugin(s).

Or maybe in generator configuration, we can add pre- and post-processors to be triggered during prisma.schema generation to do some extra stuff.

omar-dulaimi commented 2 years ago

Hello @olehmelnyk

While this might be a nice addition, it's not going to be as simple. The case of zod-prisma generator is simple because only base models schemas are generated; like Post and User. Here it's different, full CRUD schemas get generated. So the expected solution should cover all possible paths deep down. Contributions are welcomed of course, so you can give it a try if you would like.

Could you provide examples on the suggestions? Like an example on zod-to-trpc and an example on the pre and post hooks. I want to understand what you have in mind. Maybe one of them can be done.

Thank you for using this generator :)

olehmelnyk commented 2 years ago

Sure. prisma-to-trpc generator currently depends on prisma-to-zod generator. Since your prisma-to-zod generator does not support extra zod-validations via comments, and another project has that functionality (zod-prisma) - I thought it would be nice if we can run our custom middlewares/hooks before and after prisma-to-trpc is generated.

Here's an example: 1) we update prisma.schema 2) we run prisma generate to create migrations 3) prisma-to-trpc generator (or maybe new one generator with pre- and post-middlewares) runs, so we could run custom code before and after trpc is generated.

Like: