omar-dulaimi / prisma-zod-generator

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

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

Open BooleT37 opened 4 months ago

BooleT37 commented 4 months ago

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 https://github.com/omar-dulaimi/prisma-zod-generator/pull/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!