risen228 / nestjs-zod-prisma Goto Github PK
View Code? Open in Web Editor NEWZod Prisma fork for nestjs-zod
License: MIT License
Zod Prisma fork for nestjs-zod
License: MIT License
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';
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;
}
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.
Are there any plans to upgrade to prisma v4?
For anyone facing an issue with this package you can guys check my new package
https://github.com/mohrazzak/better-nestjs-zod-prisma
i fixed nullable and nullish issues
all enums issue (duplicate imports and prisma type error)
supported swagger out of the box using another package
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
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
Any interest in adding this to your library?
CarterGrimmeisen/zod-prisma#111
solves this problem: CarterGrimmeisen/zod-prisma#108
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...
Hi,
To be consistent with prisma, optional fields should be nullable
and not nullish
. See related issue in zod-prisma.
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,
}))
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!
This is important so if something new introduced to zod
We dont have to wait nestjs-zod to support it
Hi, I have following prisma model and auto generated Zod object
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?
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.1nestjs-zod
: 2.3.3nestjs-zod-prisma
: 3.0.1Is it possible to omit a field when generating a validation object?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.