@elhanmah/prisma-to-zod v0.1.1
Reasoning for the Fork
There are other libraries out there made to generate Zod schemas from Prisma models, but the reason I like this more than some alternatives is because of its simplicity and ease of use. I plan to keep this library that way and will be skeptical of adding any features that might significantly increase the complexity of the library.
The original zod-prisma library is no longer maintained. When I tried to use it, I ran into a bug that made the library unusable. More on that here.
I tried contacting the original author, but he was unresponsive, so there was no way for me to get the bug fixed. I decided to fork the project, fix the bug, publish it as a new library, and maintain it myself. I also plan to add some new features that I think would be useful.
First of all, I added better ESLint, Prettier, and TypeScript configurations/checks to the project. I also plan to bump up all of the dependencies to their latest versions so that the library is up to date, and consider switching some of the dependencies to more modern alternatives.
I also plan on keeping this library compatible with the latest versions of Prisma (currently v5.19.1) and Zod (currently v3.23.8).
About The Project
I got tired of having to manually create Zod schemas for my Prisma models and of updating them everytime I made schema changes. This provides a way to automatically generate them from your Prisma schema.
Built With
Getting Started
To get a local copy up and running follow these simple steps.
Prerequisites
This project utilizes yarn and if you plan on contributing, you should use it as well.
npm install -g yarn
Installation
Ensure your tsconfig.json enables the compiler's strict mode. Zod requires it and so do we, you will experience TS errors without strict mode enabled
Add @elhanmah/prisma-to-zod as a dev dependency
yarn add -D @elhanmah/prisma-to-zod
Add the prisma-to-zod generator to your schema.prisma
generator zod { provider = "prisma-to-zod" output = "./zod" // (default) the directory where generated zod schemas will be saved relationModel = true // (default) Create and export both plain and related models. // relationModel = "default" // Do not export model without relations. // relationModel = false // Do not generate related model modelCase = "PascalCase" // (default) Output models using pascal case (ex. UserModel, PostModel) // modelCase = "camelCase" // Output models using camel case (ex. userModel, postModel) modelSuffix = "Model" // (default) Suffix to apply to your prisma models when naming Zod schemas imports = null // (default) will import the referenced file in generated schemas to be used via imports.someExportedVariable // https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-by-null-values prismaJsonNullability = true // (default) uses prisma's scheme for JSON field nullability // prismaJsonNullability = false // allows null assignment to optional JSON fields prisma = "@prisma/client" // Path to prisma client, defaults to '@prisma/client' optionalRelations = true // (default) all relations generated on the relation schema will be optional }
Run
npx prisma generate
oryarn prisma generate
to generate your zod schemas- Import the generated schemas from your selected output location
Usage
JSDoc Generation
Rich-comments in the Prisma schema will be transformed into JSDoc for the associated fields:
Note: make sure to use a triple-slash. Double-slash comments won't be processed.
model Post {
/// The unique identifier for the post
/// @default {Generated by database}
id String @id @default(uuid())
/// A brief title that describes the contents of the post
title String
/// The actual contents of the post.
contents String
}
Generated code:
export const PostModel = z.object({
/**
* The unique identifier for the post
* @default {Generated by database}
*/
id: z.string().uuid(),
/**
* A brief title that describes the contents of the post
*/
title: z.string(),
/**
* The actual contents of the post.
*/
contents: z.string(),
})
Extending Zod Fields
You can also use the @zod
keyword in rich-comments in the Prisma schema to
extend your Zod schema fields:
model Post {
id String @id @default(uuid()) /// @zod.uuid()
/// @zod.max(255, { message: "The title must be shorter than 256 characters" })
title String
contents String /// @zod.max(10240)
}
Generated code:
export const PostModel = z.object({
id: z.string().uuid(),
title: z.string().max(255, { message: 'The title must be shorter than 256 characters' }),
contents: z.string().max(10240),
})
Importing Helpers
Sometimes it is useful to define a custom Zod preprocessor or transformer for your data. @elhanmah/prisma-to-zod enables you to reuse these by importing them via a config options. For example:
generator zod {
provider = "prisma-to-zod"
output = "./zod"
imports = "../src/zod-schemas"
}
model User {
username String /// @zod.refine(imports.isValidUsername)
}
The referenced file can then be used by simply referring to exported members via
imports.whateverExport
. The generated zod schema files will now include a
namespaced import like the following.
import * as imports from '../../src/zod-schemas'
Custom Zod Schema
In conjunction with this import option, you may want to utilize an entirely
custom zod schema for a field. This can be accomplished by using the special
comment directive @zod.custom()
. By specifying the custom schema within the
parentheses you can replace the autogenerated type that would normally be
assigned to the field.
For instance if you wanted to use
z.preprocess
JSON Fields
JSON fields in Prisma disallow null values. This is to disambiguate between setting a field's value to NULL in the database and having a value of null stored in the JSON. In accordance with this @elhanmah/prisma-to-zod will default to disallowing null values, even if your JSON field is optional.
If you would like to revert this behavior and allow null assignment to JSON
fields, you can set prismaJsonNullability
to false
in the generator options.
Examples
For examples, please refer to the Examples Directory or the Functional Tests
Roadmap
See the open issues for a list of proposed features (and known issues).
Contributing
Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature
) - Commit your Changes (
git commit -m 'Add some AmazingFeature'
) - Push to the Branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
License
Distributed under the MIT License. See LICENSE
for more information.
Contact
Elhan Mahmutovic - elhan.mahmutovic03@gmail.com
Project Link: https://github.com/elhanm/prisma-to-zod