Class generator from Prisma schema.
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?
dryRundefaults totrue, so the first run prints the classes to your terminal instead of writing them. SetdryRun = "false"in the generator block once the preview looks right — see Supported options.
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 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.
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.
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),
) {}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.
npm install --save-dev prisma-class-generatoryarn add --dev prisma-class-generatorDefine the generator in schema.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.
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:
…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[]
}
```……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.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:
@ApiProperty/@ApiPropertyOptional from @nestjs/swagger). default value is true/// doc comment (minus any @directive tokens) becomes the decorator's description — see Per-field directives below for the directives themselves@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 showinguseSwagger is — no separate option@Field from @nestjs/graphql). default value is false@IsInt, @IsString, @IsOptional, @IsEnum, @IsArray, ...) based on each field's Prisma type, for use with NestJS's ValidationPipe. default value is falsevalidateNestedRelations if the relation field is the payload you want validated as-isDateTime 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 firstBigInt/Bytes/Json fields get no type-specific validator — class-validator has no direct equivalent for those@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)@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 onesuseValidation. Adds @ValidateNested() ({ each: true } for list relations)No open issues yet, or sync has not completed.