CarterGrimmeisen / zod-prisma

A custom prisma generator that creates Zod schemas from your Prisma model.
MIT License
810 stars 86 forks source link

Wrong Zod schema when working with Decimal in Prisma model #168

Open ElhanM opened 4 months ago

ElhanM commented 4 months ago

In schema.prisma

I have:

generator zod {
  provider              = "zod-prisma"
  output                = "../../../packages/v2_wms-analytics-shared/src/zod"
  useDecimalJs          = "true" 
  modelCase             = "PascalCase"
  modelSuffix           = "Model"
  relationModel         = "true"
  prismaJsonNullability = "true"
}

So useDecimalJs is set to true

Now, I have some entities that use the Decimal type

For example:

  ...
  column_name      Decimal?  @db.Decimal(18, 4)
  ...

When I generate zod schemas for entities like these, I would simply get

  ...
  column_name: z.number().nullish(),
  ...

Now, when I query data from this table using Prisma, the columns that are of Decimal type are objects under the hood, and therefore when I try to validate this data using Zod, I get an error, something along the line of invalid_type expected number (according to schema) received object (when queried with Prisma)

If instead I would do:

  ...
  column_name: z.object().nullish(),
  ...

This would work.

Is there any workaround to this? I have a lot of schemas and do not want to change each of them. Would it be possible to make it so that, upon schema generation, for decimal types, to not use z.number().nullish(), and instead use some schema to validate the Decimal object correctly?

Also, in every schema file, on the top I have:

// Helper schema for Decimal fields
z.instanceof(Decimal)
    .or(z.string())
    .or(z.number())
    .refine(value => {
        try {
            return new Decimal(value);
        } catch (error) {
            return false;
        }
    })
    .transform(value => new Decimal(value));

What exactly does this do? Is it supposed to solve this problem? Why is it not working? See this issue

ElhanM commented 4 months ago

I think the Helper schema for Decimal fields was supposed to be a fix to this problem that got dropped somewhere along the way. Someone tried to fix it here

But, in the meantime, this also happened