0.0.15 • Published 6 months ago

zod-prisma-validation-extension v0.0.15

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

NPM Contributors Forks Stargazers Issues MIT License

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-validation-extension as a dev dependency

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

    generator zod {
      provider                 = "zod-prisma-validation-extension"
      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)
    
    }
  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-validation-extension enables you to reuse these by importing them via a config options. For example:

generator zod {
  provider      = "zod-prisma-validation-extension"
  output        = "./zod"
}

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

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 - Carter.Grimmeisen@uah.edu

Project Link: https://github.com/chrisrydahl/zod-prisma-validation-extension

0.0.12

6 months ago

0.0.13

6 months ago

0.0.14

6 months ago

0.0.15

6 months ago

0.0.11

6 months ago

0.0.10

6 months ago

0.0.9

6 months ago

0.0.8

6 months ago

0.0.7

6 months ago

0.0.6

6 months ago

0.0.5

6 months ago

0.0.4

6 months ago

0.0.3

6 months ago

0.0.2

6 months ago

0.0.1

6 months ago