omar-dulaimi / prisma-zod-generator

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

Resolves #88 - satisfies type instead of inferring #89

Open owenr88 opened 11 months ago

owenr88 commented 11 months ago

Description

See #88 in reference to the issue. This implements the satisfies keyword for the type instead of inferring the zodType directly.

import { z } from 'zod';

import type { Prisma } from '@prisma/client';

const Schema = z
  .object({
    id: z.number().optional(),
    email: z.string().optional(),
  })
  .strict() satisfies z.ZodType<Prisma.UserWhereUniqueInput>;

export const UserWhereUniqueInputObjectSchema = Schema;

With the above, you can now

const ExtendedSchema = UserWhereUniqueInputObjectSchema.extend({
  example: z.string()
})
// And
const ExampleSchema = UserWhereUniqueInputObjectSchema.shape.example;

References

Fixes #88. And a similar discussion in the zod repo.

owenr88 commented 11 months ago

I've done a little more investigating and it seems this has an unintended effect on schemas with z.lazy() where it makes the type an any. Argh! I've marked this PR as draft for now.

Screenshot 2023-10-27 at 11 38 25

Any suggestions how we could get around this? One solution is keeping the original, but also exposing the raw z.object schema:

const Schema = z
  .object({
    id: z.number().optional(),
    email: z.string().optional(),
  })
  .strict() satisfies z.ZodType<Prisma.UserWhereUniqueInput>;

export const _UserWhereUniqueInputObjectSchema = Schema;
export const UserWhereUniqueInputObjectSchema: z.ZodType<Prisma.UserWhereUniqueInput> = Schema;

Keen for thoughts on this!

angelinashepherd commented 7 months ago

hi omar, thank you so much for this extremely helpful library! Is it possible for you to make it compatible with Prisma 5 as well?