All Projects → CarterGrimmeisen → zod-prisma

CarterGrimmeisen / zod-prisma

Licence: MIT license
A custom prisma generator that creates Zod schemas from your Prisma model.

Programming Languages

typescript
32286 projects

Labels

Projects that are alternatives of or similar to zod-prisma

calendso
Scheduling infrastructure for absolutely everyone.
Stars: ✭ 13,100 (+3653.58%)
Mutual labels:  prisma, zod
fastify-graphql-nexus-prisma
GraphQL Server with Fastify, Mercurius, Prisma, and Nexus
Stars: ✭ 125 (-64.18%)
Mutual labels:  prisma
prisma-dbml-generator
Prisma DBML Generator
Stars: ✭ 434 (+24.36%)
Mutual labels:  prisma
Ararat
Ararat is the next-generation container/virtual machine control panel. It is your one-stop shop for single application containers, full system containers, and KVM instances
Stars: ✭ 21 (-93.98%)
Mutual labels:  prisma
fullstack-graphql-app
An opinionated fullstack GraphQL monorepo boilerplate using pnpm, Turborepo, Prisma, GraphQL Yoga 2, Fastify, Nextjs, urql, and React
Stars: ✭ 90 (-74.21%)
Mutual labels:  prisma
mrapi
A framework for rapid development of API or DAL applications.
Stars: ✭ 20 (-94.27%)
Mutual labels:  prisma
prisma-pg-jest
Example showcasing how to use Prisma + Postgres + Jest, where each test has its own unique DB context
Stars: ✭ 103 (-70.49%)
Mutual labels:  prisma
workshop-serverless-graphql
[AWSKRUG Serverless Group 2019] Serverless GraphQL Workshop
Stars: ✭ 80 (-77.08%)
Mutual labels:  prisma
fullstack-nextjs-ecommerce
Fullstack Next.js E-Commerce made with NextAuth + Prisma, Docker + TypeScript + React Query + Stripe + Tailwind Sentry and much more 🛒
Stars: ✭ 524 (+50.14%)
Mutual labels:  prisma
cms30
🙌 #CMS30 | Free 30 CMS templates
Stars: ✭ 23 (-93.41%)
Mutual labels:  prisma
boilerplate
Boilerplate for @prisma-cms
Stars: ✭ 22 (-93.7%)
Mutual labels:  prisma
prisma-ecommerce
No description or website provided.
Stars: ✭ 44 (-87.39%)
Mutual labels:  prisma
nikolovlazar.com
My personal site's repo built using Next.js, Chakra UI, MDX, Prisma, PlanetScale.
Stars: ✭ 126 (-63.9%)
Mutual labels:  prisma
react-native-instagram-clone
Instagram Clone (light version) — Graphql + React (ios, android, web)
Stars: ✭ 29 (-91.69%)
Mutual labels:  prisma
prisma-json-schema-generator
A generator for Prisma 2 to generate a valid JSON Schema (v7)
Stars: ✭ 145 (-58.45%)
Mutual labels:  prisma
nest-next-sample
NestJS + Next.js sample application / Backend and Frontend use only TypeScript!!!
Stars: ✭ 110 (-68.48%)
Mutual labels:  prisma
react-chat-app
A real-time chat application with Node.js, Prisma, GraphQL, Next.js, React.js and Apollo.
Stars: ✭ 61 (-82.52%)
Mutual labels:  prisma
prismabuilder.io
Build your Prisma schema visually in this easy-to-use web based tool
Stars: ✭ 161 (-53.87%)
Mutual labels:  prisma
midwayjs-crud
基于 Typescript+MidwayJs+Nacos 的微服务开发架构
Stars: ✭ 45 (-87.11%)
Mutual labels:  prisma
redwood
The App Framework for Startups
Stars: ✭ 15,079 (+4220.63%)
Mutual labels:  prisma

NPM Contributors Forks Stargazers Issues MIT License


Logo

Zod Prisma

A custom prisma generator that creates Zod schemas from your Prisma model.
Explore the docs »

View Demo · Report Bug · Request Feature

Table of Contents

  1. About The Project
  2. Getting Started
  3. Usage
  4. Examples
  5. Roadmap
  6. Contributing
  7. License
  8. Contact

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 of automatically generating them with your prisma

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 too.

npm install -g yarn

Installation

  1. 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

  2. Add zod-prisma as a dev dependency

    yarn add -D zod-prisma
  3. Add the zod-prisma generator to your schema.prisma

    generator zod {
      provider                 = "zod-prisma"
      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
    
      // useDecimalJs          = false // (default) represent the prisma Decimal type using as a JS number
      useDecimalJs             = true // represent the prisma Decimal type using Decimal.js (as Prisma does)
    
      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
    }
  4. Run npx prisma generate or yarn prisma generate to generate your zod schemas

  5. Import the generated schemas form 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 its useful to define a custom Zod preprocessor or transformer for your data. zod-prisma enables you to reuse these by importing them via a config options. For example:

generator zod {
  provider      = "zod-prisma"
  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 zod-prisma 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.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

Distributed under the MIT License. See LICENSE for more information.

Contact

Carter Grimmeisen - [email protected]

Project Link: https://github.com/CarterGrimmeisen/zod-prisma

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].