omar-dulaimi / prisma-zod-generator

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

{Model}Include.schema.ts is generated for models that do not have a relation to any other models #36

Closed BitPhoenix closed 2 years ago

BitPhoenix commented 2 years ago

Bug description

Tagging @Shahidul1004 in this one as you might have some good insights here as well

I noticed that {Model}Include.schema.ts is generated for models that do not have a relation to any another model and the result looks something like this:

const Schema: z.ZodType<Prisma.{Model}Include> = z.object({}).strict();

There is an error line under Prisma.{Model}Include because it looks like Prisma only generates a {Model}Include type if the model contains a relation to another model. So the generated {Model}Include.schema.ts is referencing a Prisma type that does not exist đŸ˜­

As a fix, I believe this section in include-helpers needs to be wrapped in an if condition checking for hasRelation, where hasRelation is set to true if we encounter isRelationField === true

...
let hasRelation = false;
...
if (isRelationField) {
  hasRelation = true;
}
...
if (hasRelation) {
  const modelIncludeInputObjectType: DMMF.InputType = {
        name: `${modelName}Include`,
        constraints: {
          maxNumFields: null,
          minNumFields: null,
        },
        fields,
      };
      modelIncludeInputObjectTypes.push(modelIncludeInputObjectType);
}

@Shahidul1004 Curious if you're able to reproduce this and see if the fix works đŸ¤”

How to reproduce

Run npm run generate-example with a schema.prisma containing a model with no relation to another model, and look at the generated {Model}Include.schema.ts file that is generated.

model Test {
  id Int @unique
}

Expected behavior

Expected behavior: {Model}Include.schema.ts is not generated for models that don't have relations with any other models.

Prisma information

The schema.prisma in this repo, just including a model that does not have a relation with any other model.

model Test {
  id Int @unique
}

Environment & setup

Mac OS + included schema.prisma if you add a model that does not have a relation with any other model

model Test {
  id Int @unique
}

Prisma Version

N / A

BitPhoenix commented 2 years ago

Added pull request with proposed fix: https://github.com/omar-dulaimi/prisma-zod-generator/pull/38

Note: updated fix implementation slightly from original comment above

omar-dulaimi commented 2 years ago

Hey @BitPhoenix Thank you for your continued work on this and the other project. I'll be taking a look at your PR now.