Prisma 2+ generator to emit typescript models of your database with class validator
npm install @serviceup/prisma-generator-class-validatorAutomatically generate typescript models of your database with class validator validations ready, from your Prisma Schema. Updates every time npx prisma generate runs.
- Supported Prisma Versions
- Installation
- Usage
- Additional Options
- Development
- Running Tests
``bash`
npm install prisma-generator-class-validator
1- Add the generator to your Prisma schema
`prisma`
generator class_validator {
provider = "prisma-generator-class-validator"
}
3- Running npx prisma generate for the following schema.prisma
`prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String?
published Boolean @default(false)
viewCount Int @default(0)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
rating Float
}
`
will generate classes as follows:
User:
`ts
import { IsInt, IsDefined, IsString, IsOptional } from 'class-validator';
import { Post } from './';
export class User {
@IsDefined()
@IsInt()
id!: number;
@IsDefined()
@IsString()
email!: string;
@IsOptional()
@IsString()
name?: string | null;
@IsDefined()
posts!: Post[];
}
`
| Option | Description | Type | Default |
| -------- | ----------------------------------------- | -------- | ------------- |
| output | Output directory for the generated models | string | ./generated |
Use additional options in the schema.prisma
`prisma`
generator class_validator {
provider = "prisma-generator-class-validator"
output = "./generated-models"
}
This is a Prisma generator that creates TypeScript class models with class-validator decorators based on your Prisma schema.
1. Clone the repository
2. Install dependencies: npm installnpm run build
3. Build the project: npm test
4. Test the generator:
The project includes tests for the helper functions:
`bashRun helper function tests (most reliable)
npm test
$3
Integration tests require a valid Prisma schema and can be more fragile. They're best run in a controlled environment where all dependencies are properly set up.
For regular development, stick to the helper tests (
npm test`) which are faster and more reliable.