Code Monkey home page Code Monkey logo

nestjs-zod-prisma's People

Contributors

riccardo-ditosto-gellify avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nestjs-zod-prisma's Issues

Duplicate enum import

There is something wrong with nestjs-zod
Here is an example explaining what i am talking about

model User {
firstEnum TestEnum
seondEnum TestEnum
}

enum TestEnum {
FIRST
SECOND
}

This is resulting duplicated import for the TestEnum in the User zod generated schema which is resulting to an error

import { TestEnum , TestEnum } from './enums';

DTO support for ApiProperty

can we add a confg like generateDTO for swagger to add api property

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

  generateDto              = true // (default) Generate DTOs for NestJS
  generateSwaggerApiProperty = true // (default) Genrate ApiPrpoertyDecorator on DTO's
  ...
  

From schema.prisma

model User {
  id                String   @id /// @z.string()
  email             String   @unique /// @z.string().email() @ApiProperty({ example: '[email protected]', description: 'User email' })
  full_name         String   @unique /// @z.string().max(50, { message: "Fullname should be less than 50 characters " }) @ApiProperty({ example: 'Jean Doe', description: 'Users full name' })
  password          String   @unique /// @z.password().atLeastOne('digit').atLeastOne('lowercase').atLeastOne('uppercase').min(8).max(100) @ApiProperty({ description: 'User password' })
}

To Generate example

export class UserDto {
  @ApiProperty({ example: '[email protected]', description: 'User email' })
  email: string;
  @ApiProperty({ example: 'Jean Doe', description: 'Users full name' })
  full_name: string;
  @ApiProperty({ description: 'User password' })
  password: string;
}

Dependency conflict

Hi, any plan on resolving this for the newest version, or do I have to downgrade?

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: xyz
npm ERR! Found: [email protected]
npm ERR! node_modules/nestjs-zod
npm ERR!   nestjs-zod@"^2.3.3" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer nestjs-zod@"^1.1.0" from [email protected]
npm ERR! node_modules/nestjs-zod-prisma
npm ERR!   dev nestjs-zod-prisma@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Use custom zod schema from imported zod schemas

How can I use a custom schema/type for validating a field?

Example:

// my custom schema
export const MyType = z.union([z.literal("a"),z.literal("b")])

// prisma schema
  type      String? /// @imports.MyType
  
// zod/entity.ts
import * as imports from "../zod-schemas"

// (added this manually to show what I would expect, instead there is a multi-line comment with the contents behind "///" above this following statement)
  type: imports.MyType, // imported from my custom schemas

[feature request]: support reading `db.VarChar` and limit string length in zod via `.minLength().maxLength()`

Hi, I usually define model schema like this.

model Post {
  id       String    @id @default("")
  slug     String    @unique @db.VarChar(80)
  text     String
  title    String    @db.VarChar(255)
  created  DateTime  @default(now()) @map("created_at")
  modified DateTime? @updatedAt @map("updated_at")

  @@index([slug])
  @@index([created])
}

I use @db.VarChar(80) to define slug as a length-limited string. So if the generated schema is like this, it should be so cool.

export const PostModel = z.object({
  id: z.string(),
  slug: z.string().minLength(0).maxLength(80),
  text: z.string(),
  title: z.string(),
  created: z.date(),
  modified: z.date().nullish(),
})

Thank you for your support

clashing interpretation of enums

Hi there,
Have been using this package for a while now and it has saved me a lot of time! Thank you.
One issue that I have been regularly facing is that enums from Prisma's generated client are of the form:

/**
 * Enums
 */

export const Role: {
  admin: 'admin',
  customer: 'customer'
};

export type Role = (typeof Role)[keyof typeof Role]

However nestjs-zod-prisma exports actual TS enums:

export enum Role {
  admin = "admin",
  customer = "customer"
}

I prefer that actual enums are exported, but often find that I have issues when I use the types/schemas generated by Prisma client and nestjs-zod-prisma interchangeably:

Type 'import("/Users/oldo/node_modules/.prisma/client/index").Role' is not assignable to type 'import("/Users/oldo/packages/zod/src/enums").Role'.
Type '"admin"' is not assignable to type 'Role'.

Would it be possible to generate enums in the same way as Prisma client does? As far as I can tell, there is no way to modify the way Prisma client generates enums...

Will generate unnecessary import `import * as imports from "../../prisma/null"` when set `imports = null` in generator zod

When I set imports = null, will generate unnecessary import import * as imports from "../../prisma/null".

generator zod {
  provider = "nestjs-zod-prisma"
  output   = "../src/schemas" // (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

  generateDto = true // (default) Generate DTOs for NestJS

  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

  dtoCase = "PascalCase" // (default) Output DTOs using pascal case (ex. UserDto, PostDto)
  // dtoCase             = "camelCase" // Output DTOs using camel case (ex. userDto, postDto)

  dtoSuffix = "Dto" // (default) Suffix to apply to your prisma models when naming DTOs

  // 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
}
import * as z from "nestjs-zod/z"
import { createZodDto } from "nestjs-zod/dto"
import * as imports from "../../prisma/null" // what is this null ????
import { CompleteUser, RelatedUserModel } from "./index"

export const ApiTokenModel = z.object({
  id: z.string(),
  userId: z.string(),
  created: z.date(),
  token: z.string(),
  expired: z.date().nullish(),
  name: z.string(),
})

export class ApiTokenDto extends createZodDto(ApiTokenModel) {
}

export interface CompleteApiToken extends z.infer<typeof ApiTokenModel> {
  user: CompleteUser
}

/**
 * RelatedApiTokenModel contains all relations on your model in addition to the scalars
 *
 * NOTE: Lazy required in case of potential circular dependencies within schema
 */
export const RelatedApiTokenModel: z.ZodSchema<CompleteApiToken> = z.lazy(() => ApiTokenModel.extend({
  user: RelatedUserModel,
}))

Not an issue, just a thanks

Hi @risenforces
I just wanted to leave a message for you to say thanks for developing this library. It's extremely useful and saving a lot of work and double handling. Cheers!

How to adjust generated DTO, for example exclude auto incremented ID property?

Hi, I have following prisma model and auto generated Zod object
image

I am trying to use it when adding a new Article. But generated DTO has id property as optional. Prisma client expects id to never exist. How should I handle this?

I am able to use Omit to handle just the issue of id property but then it creates another issues, for example that title is optional in my DTO but it's required by prisma model.

I am looking for optimal way of handling this, so that I don't have to create multiple classes, types or interfaces.

Edit: I see that type inferred from Zod, gives my optional title property, while it should be required. Is there a way around this?
image

Wrong z.instanceof generation

Hi,

I have a prisma model that is defined as bytes. By using this generator, the zod schema validator is generating a wrong z.instanceOf(Buffer) instead z.instanceof(Buffer) by displaying this error

Property 'instanceOf' does not exist on type 'typeof import("/home/user/projects/api/node_modules/nestjs-zod/z")'. Did you mean 'instanceof'?ts(2551)

This is occuring by using the library versions:

  • prisma: 5.1.1
  • @prisma/client: 5.1.1
  • nestjs-zod: 2.3.3
  • nestjs-zod-prisma: 3.0.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.