Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

prisma-class-generator

> 后端框架
Open source

Class generator from Prisma schema.

190 stars0 likes3 views
WebsiteGitHub

About

Class generator from Prisma schema.

Prisma Class Generator

See CHANGELOG.md for release notes. Found a bug or want a feature? Open an issue. Have a "how do I...?" question instead? Ask in Discussions — it's faster for you and keeps the issue tracker focused on actual bugs.

Contents · Usage · Supported options · Per-field directives · Databases · Prisma versions · Features · Comparison with similar tools · FAQ

In a hurry? dryRun defaults to true, so the first run prints the classes to your terminal instead of writing them. Set dryRun = "false" in the generator block once the preview looks right — see Supported options.

Prisma

Prisma is a database ORM library for Node.js and TypeScript.

Prisma generates each model's type definitions directly from schema.prisma, so no additional entry classes or repository layers are required.

That works well on its own, but it runs into a limitation with frameworks like NestJS: to use @nestjs/swagger, an entity has to be defined as a class, and Prisma Client's generated types aren't classes.

This tool closes that gap — it generates a TypeScript file per model based on schema.prisma. The generated classes are formatted with prettier, using the user's prettier config file if present, so defining classes by hand is no longer necessary while schema.prisma stays the single source of truth.

Prisma Client's returned objects don't include a model's relational fields. This generator can produce two separate files per model instead — one that matches Prisma Client's own interface, and one that holds only the relational fields — by setting the separateRelationFields option to true. The default value is false.

NestJS

NestJS is a framework for building efficient, scalable Node.js server-side applications.

NestJS builds on classes and decorators as its basic structure. Defining a model as a class, as below, makes it straightforward to apply Swagger, TypeGraphQL, and similar tools through decorators — and regenerating the class whenever schema.prisma changes keeps the two in sync.

typescript
export class Company {
	@ApiProperty({ type: Number }) // swagger
	@Field((type) => Int) // TypeGraphQL
	id: number

	@ApiProperty({ type: String }) // swagger
	name: string

	@ApiProperty({ type: Boolean }) // swagger
	isUse: boolean
}

With separateRelationFields set to true, the two generated classes can be composed into a class that contains only the relations you actually want. The example below uses @nestjs/swagger's composition helpers to create a class with all of Product's own properties plus just the category relation from the generated relations class.

typescript
import { IntersectionType, PickType } from '@nestjs/swagger'
import { Product } from './product'
import { ProductRelations } from './product_relations'

export class ProductDto extends IntersectionType(
	Product,
	PickType(ProductRelations, ['category'] as const),
) {}

Usage

  1. Install — as a dev dependency: it runs as part of prisma generate and the classes it writes don't import it, so it never needs to ship to production.

    bash
    npm install --save-dev prisma-class-generator
    bash
    yarn add --dev prisma-class-generator
  2. Define the generator in schema.prisma

    prisma
    generator prismaClassGenerator {
        provider = "prisma-class-generator"
    }

    This generator reads the Prisma Client generator declared in the same schema to figure out where the client lives, so make sure one is present too — either the legacy provider = "prisma-client-js" or the newer provider = "prisma-client" (default since Prisma 7). Both are supported.

  3. Check the generated files

    Given these models in schema.prisma — this is the exact Product/Category/Company example from prisma/postgresql.prisma, the same schema this repo's own CI golden test runs against, so it won't drift out of sync with the real generator again:

…
bash
these classes are generated in /src/\_gen/prisma-class — this is the real,
unedited output of running the generator against the schema above:

( The generating path can be customized through _output_ option. )

```typescript
// category.ts
import { Product, type Product as ProductAsType } from './product'
import { ApiProperty } from '@nestjs/swagger'

export class Category {
	@ApiProperty({ type: Number })
	id: number

	@ApiProperty({ isArray: true, type: () => Product })
	products: ProductAsType[]
}
```
…
…
bash
Note that optional fields with a schema-level default (`isShown`, `stock`, `totalIncome`,
the `tags*`/`numTags*` arrays above) are generated with that default value already
assigned, so a `new Product()` starts in a valid state without every caller having to set
them. And notice that relation fields (`category`/`company`/`products` above) import both
the real class *and* a `type ... as ...AsType` alias — the field's own type annotation uses
the alias to avoid a circular-import crash under `emitDecoratorMetadata`; see this repo's
[CLAUDE.md](./CLAUDE.md) if you're curious why.

```typescript
// index.ts
import { Product as _Product } from './product'
import { Category as _Category } from './category'
import { Company as _Company } from './company'

export namespace PrismaModel {
	export class Product extends _Product {}
	export class Category extends _Category {}
	export class Company extends _Company {}

	export const extraModels = [Product, Category, Company]
}
```

Classes are grouped into the `PrismaModel` namespace and re-exported through `index.ts` for
two reasons:

1. Generated class names can otherwise collide with the model types Prisma itself generates.
2. When wiring up Swagger in NestJS, `extraModels` can point at this one array instead of
   listing every generated class individually in bootstrap code.

For example:

```typescript
// main.ts in a NestJS application
import { PrismaModel } from './_gen/prisma-class'

const document = SwaggerModule.createDocument(app, options, {
	extraModels: [...PrismaModel.extraModels],
})
```

You can also disable it through the _makeIndexFile_ option.

Supported options

Every value is written as a string in schema.prisma (dryRun = "false", not dryRun = false) — that's how Prisma passes generator config through.

option default what it does
output ../src/_gen/prisma-class where the files are written
dryRun true print to the terminal instead of writing. Set to "false" to actually generate files
makeIndexFile true also emit index.ts with the PrismaModel namespace and extraModels
makeDtoFiles false also emit Create/Update, composed with NestJS mapped types
separateRelationFields false move relation fields into a separate Relations class
useSwagger true @ApiProperty/@ApiPropertyOptional, plus description/example from the schema
useGraphQL false TypeGraphQL's @Field and @ObjectType
useValidation false class-validator decorators, sharpened by @db.* native types on Prisma 6+
validateNestedRelations false adds @ValidateNested() to relation/composite fields (needs useValidation)
useSerialization false class-transformer @Exclude()/@Expose()/@Type()
useNonNullableAssertions false ! on non-optional fields, for TypeScript strict mode
preserveDefaultNullable false type nullable fields as | null instead of making them optional
useUndefinedDefault false = undefined for fields with no default
preserveDecimal false Prisma.Decimal instead of number for Decimal fields
clientImportPath @prisma/client where generated enums and the Prisma namespace are imported from

Details for each:

  • dryRun
    • Controls whether files are written to disk or just printed to the terminal. default value is true
      • once the printed preview looks right, set this option to false to actually write the files
  • output
    • sets output path. default is '../src/_gen/prisma-class'
  • useSwagger
    • generates swagger decorator (@ApiProperty/@ApiPropertyOptional from @nestjs/swagger). default value is true
      • a field's /// doc comment (minus any @directive tokens) becomes the decorator's description — see Per-field directives below for the directives themselves
      • a literal @default(...) (e.g. @default("abc"), @default(1), an enum default) becomes the decorator's example. Function-based defaults (now(), autoincrement(), dbgenerated()) and BigInt/DateTime defaults are skipped — there's no single literal worth showing
      • both are derived straight from the schema, not guessed, so they're always on when useSwagger is — no separate option
  • useGraphQL
    • generates TypeGraphQL decorator (@Field from @nestjs/graphql). default value is false
  • useValidation
    • generates class-validator decorators (@IsInt, @IsString, @IsOptional, @IsEnum, @IsArray, ...) based on each field's Prisma type, for use with NestJS's ValidationPipe. default value is false
      • relation and composite-type fields are intentionally left without a type-specific validator: validating one means assuming a shape for the nested payload, which the schema doesn't state. Turn on validateNestedRelations if the relation field is the payload you want validated as-is
      • DateTime fields use @IsDateString() rather than @IsDate(), so it validates the raw string a JSON request body actually contains without requiring class-transformer's @Type(() => Date) to run first
      • BigInt/Bytes/Json fields get no type-specific validator — class-validator has no direct equivalent for those
      • a field's @db.* native type sharpens the validator further when it describes a real constraint, on Prisma 6+ only (Prisma 5's DMMF doesn't expose native types at all — this silently falls back to the type-based validator above, no error): @db.Uuid/ @db.UniqueIdentifier → @IsUUID(), MongoDB's @db.ObjectId → @IsMongoId(), postgresql/cockroachdb's @db.Inet → @IsIP() (all three replace the generic @IsString()), @db.VarChar(n)/@db.Char(n)/sqlserver's N-prefixed variants/ cockroachdb's @db.String(n) → @IsString() + @MaxLength(n), MySQL's unsigned integer types → @IsInt() + @Min(0)
        • deliberately not covered: MySQL's @db.UnsignedBigInt — it maps to Prisma's BigInt scalar, and class-validator's @Min()/@Max() require typeof value === 'number', which a BigInt value never satisfies (its typeof is 'bigint') — adding it would reject every value, including valid ones
  • validateNestedRelations
    • requires useValidation. Adds @ValidateNested() ({ each: true } for list relations)

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptgeneratornestjsprismaswagger

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架