Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ElhanM opened this issue May 22, 2024 · 1 comment
Open

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

ElhanM opened this issue May 22, 2024 · 1 comment

Comments

@ElhanM
Copy link

ElhanM commented May 22, 2024

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 ElhanM changed the title Now working with Decimal in Prisma model - wrong schema Wrong Zod schema when working with Decimal in Prisma model May 22, 2024
@ElhanM
Copy link
Author

ElhanM commented May 29, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant