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

Option to use z.instanceof(Decimal) for Decimal fields #94

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

BooleT37
Copy link

@BooleT37 BooleT37 commented Jun 28, 2024

Description

I have a side project that since recently uses Decimal type for some Prisma table columns. I also uses zod types for requests validation, auto-generated by your library (example). The decimal fields are converted to Decimal class automatically by superjson, so that I don't have to do any extra convertations on server side and can pass them straight to Prisma. But unfortunately, my validations now fail since prisma-zod-generator treats all decimal fields as numbers. This PR aims to fix that.

This is a continuation of #12. You said that "in the future decimal.js support may get added" so I decided to do it myself, since I need it anyway to unblock my project.

Since simply replacing the z.number() with z.instanceof(Decimal) would break backward compatibility, I opted out to introduce a new generator option for it, that is disabled by default. I don't think that this behaviour can be enabled by default even if we do a major version bump, since it assumes that we use Decimal.js library for Decimal fields, which might not be the case for all our users.

I am happy to make some tests for this functionality, but I couldn't find any way to create them in this codebase.

This is just a proposition for the implementation, though, fully functional. If you have another way of implementing it in mind, let me know. Hoping for a constructive discussion!

result.push(
this.wrapWithZodValidators('z.instanceof(Decimal)', field, inputType),
);
this.addSchemaImport('Decimal');
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might be a questionable decision, but I couldn't find any better way to add an import { Decimal } from 'decimal.js' for all schemas with Decimal fields

@BooleT37 BooleT37 changed the title Add useDecimalLib option Option to use z.instanceof(Decimal) for Decimal fields Jun 28, 2024
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

Successfully merging this pull request may close these issues.

1 participant