@inhanbyeol/prisma-class-generator
v1.0.6
Published
Prisma Schema(`schema.prisma`)를 파싱하여 **NestJS + Swagger `@ApiProperty` + `class-validator` / `class-transformer`**가 완벽하게 결합된 TypeScript 클래스(Model 및 DTO)를 자동으로 생성해 주는 Prisma Generator 라이브러리입니다.
Readme
Prisma Class Generator
Prisma Schema(schema.prisma)를 파싱하여 **NestJS + Swagger @ApiProperty + class-validator / class-transformer**가 완벽하게 결합된 TypeScript 클래스(Model 및 DTO)를 자동으로 생성해 주는 Prisma Generator 라이브러리입니다.
특징
- 완벽한 NestJS 호환:
@nestjs/swagger의@ApiProperty()및 DTO 검증용 데코레이터(class-validator,class-transformer)가 자동 부착됩니다. - 분리된 진입점 제공: Model(순수 타입 및 Swagger 속성)과 DTO(검증 데코레이터 포함)를 독립적으로 제어하고 각각 다른 경로에 생성할 수 있습니다.
- 강력한 커스텀 데코레이터 설정:
Boolean,BigInt,Decimal과 같은 특수 타입의 검증・형변환용 데코레이터 경로를 개발자가 직접schema.prisma상에서 강제 및 커스텀할 수 있어 특정 프로젝트 구조에 불필요하게 종속되지 않습니다. - 유연한 네이밍 규칙: 조직별 코딩 컨벤션에 맞춰 클래스 및 파일의 Prefix/Suffix를 자유롭게 설정 가능합니다.
설치
npm install -D @inhanbyeol/prisma-class-generator(참고: 생성된 DTO 클래스들을 사용하려면 해당 프로젝트(NestJS 등)에 @nestjs/swagger, class-validator, class-transformer가 이미 설치되어 있어야 합니다.)
사용 방법 (schema.prisma)
schema.prisma 파일 내부에 Model과 DTO 제너레이터를 각각 추가하여 사용합니다.
// 1. Model 생성기 (순수 속성 + Swagger ApiProperty)
generator model {
provider = "@inhanbyeol/prisma-class-generator"
type = "model"
output = "./generated-model"
// (선택) Prisma Client import 경로 설정 (기본값: ../../database/prisma/client)
prismaClientPath = "@prisma/client"
// (선택) 네이밍 규칙 설정
fileSuffix = ".model.ts"
}
// 2. DTO 생성기 (속성 + Swagger + Validator & Transformer 데코레이터)
generator dto {
provider = "@inhanbyeol/prisma-class-generator"
type = "dto"
output = "./generated-dto"
prismaClientPath = "@prisma/client"
// (선택) 네이밍 규칙 설정
filePrefix = "base-"
classPrefix = "Req"
classSuffix = "Dto"
fileSuffix = ".dto.ts"
// (필수) Boolean, BigInt, Decimal 타입 사용 시 데코레이터 경로 명시
isBooleanName = "MyBool"
isBooleanPath = "@/custom/bool"
isBigIntName = "ValidBigInt"
isBigIntPath = "@/custom/bigint-val"
bigIntTransformName = "TransBigInt"
bigIntTransformPath = "@/custom/bigint-trans"
isDecimalName = "ValidDecimal"
isDecimalPath = "@/custom/decimal-val"
decimalTransformName = "TransDecimal"
decimalTransformPath = "@/custom/decimal-trans"
}
model User {
id Int @id @default(autoincrement()) /// 유저 고유 ID
email String @unique /// 이메일 주소
name String? /// 이름
isActive Boolean @default(true) /// 활성 상태 여부
}생성하기:
npx prisma generate설정(Config) 옵션 명세
제너레이터 블록 안에서 설정할 수 있는 옵션들입니다.
1. 일반 설정
| 옵션명 | 기본값 | 설명 |
| :- | :- | :- |
| type | (필수) | 생성할 파일의 타입입니다. ("model" 또는 "dto") |
| output | (필수) | 생성된 클래스 파일들이 저장될 디렉터리 경로입니다. |
| prismaClientPath | ../../database/prisma/client | 생성된 파일에서 Prisma 및 $Enums 객체를 import 해올 때 사용할 기본 경로입니다. |
| exportBarrel | "false" | "true" 지정 시, 생성된 파일들을 하나로 묶어 export하는 *-export.ts 배럴 파일이 만들어집니다. |
타입 매핑 규칙 (Type Mapping)
Prisma 스키마의 필드 타입이 각각 어떤 TypeScript 타입과 데코레이터로 변환되는지 보여주는 매핑 테이블입니다. (Model은 순수 타입과 Swagger만, DTO는 검증/변환 데코레이터까지 모두 포함하여 생성됩니다.)
| Prisma 타입 | TS 타입 (Model / DTO) | Swagger (@ApiProperty) | 검증 데코레이터 (Validator) | 변환 데코레이터 (Transformer) |
| :--- | :--- | :--- | :--- | :--- |
| String | string | { type: String } | @IsString(), (필수 시 @IsNotEmpty()) | @Type(() => String) |
| Int | number | { type: Number } | @IsInt() | @Type(() => Number) |
| Float | number | { type: Number } | @IsNumber() | @Type(() => Number) |
| Boolean | boolean | { type: Boolean } | Custom (isBooleanName) | - |
| DateTime | Date | { type: Date } | @IsDate() | @Type(() => Date) |
| Decimal | Prisma.Decimal | { type: String, example: '0' } | Custom (isDecimalName) | Custom (decimalTransformName) |
| BigInt | bigint | { type: String } | Custom (isBigIntName) | Custom (bigIntTransformName) |
| Enum | string | { enum: $Enums... } | @IsEnum($Enums...) | @Type(() => String) |
| 배열 [] | Type[] | { ..., isArray: true } | @IsArray(), (각 데코레이터에 { each: true } 추가) | @Transform() (단일 값 입력 시 배열로 강제 변환 처리 추가) |
참고:
BigInt와Decimal타입은 기본 JSON 시리얼라이즈 시 문제가 발생하기 쉬워, Swagger 상에서는 편의성 및 데이터 손실 방지를 위해{ type: String }으로 매핑됩니다.
2. 네이밍 컨벤션 설정 (class & file)
| 옵션명 | 기본값 | 설명 |
| :- | :- | :- |
| classPrefix | (없음) | 생성될 TypeScript 클래스의 접두사 (예: classPrefix="Base" → BaseUser) |
| classSuffix | Dto (DTO), 없음 (Model) | 생성될 TypeScript 클래스의 접미사 (예: classSuffix="Req" → UserReq) |
| filePrefix | (없음) | 생성될 파일명 접두사 (예: filePrefix="req-" → req-user.dto.ts) |
| fileSuffix | .dto.ts 또는 .model.ts | 생성될 파일명명 규칙 및 확장자 (예: fileSuffix=".entity.ts" → user.entity.ts) |
3. 특수 타입 커스텀 데코레이터 설정 (DTO 전용)
주의: 해당 제너레이터는 프로젝트가 알 수 없는 디폴트 데코레이터 경로에 의존하는 것을 극도로 경계합니다! 만약 데이터베이스 스키마 내에
Boolean,BigInt,Decimal타입이 하나라도 존재할 경우, 상응하는 데코레이터 설정(경로및이름)을 제너레이터 옵션에 명시하지 않으면 에러를 발생시켜 강제로 설정을 요구합니다.
Boolean 타입 설정
isBooleanName: 예)"IsCustomBoolean"isBooleanPath: 예)"@/common/decorators/is-boolean"
BigInt 타입 설정
isBigIntName/isBigIntPathbigIntTransformName/bigIntTransformPath
Decimal 타입 설정
isDecimalName/isDecimalPathdecimalTransformName/decimalTransformPath
출력 예시 (Generated Code)
위 User 모델을 기반으로 생성된 base-user.dto.ts의 결과물입니다:
import { ApiProperty } from '@nestjs/swagger';
import { Prisma } from '@prisma/client';
import { IsInt, IsNotEmpty, IsString } from 'class-validator';
import { MyBool } from '@/custom/bool';
import { Type } from 'class-transformer';
// -
export class ReqUserDto {
/** 유저 고유 ID */
@ApiProperty({ type: Number })
@Type(() => Number)
@IsInt()
id!: number;
/** 이메일 주소 */
@ApiProperty({ type: String })
@Type(() => String)
@IsNotEmpty()
@IsString()
email!: string;
/** 이름 */
@ApiProperty({ type: String, nullable: true })
@Type(() => String)
@IsString()
name!: string;
/** 활성 상태 여부 */
@ApiProperty({ type: Boolean })
@MyBool() // <-- 커스텀 데코레이터 퍼펙트 매핑!
isActive!: boolean;
}개발 및 기여
버그를 발견하거나 제안하고 싶은 개선사항이 있다면 Issue나 PR을 부탁드립니다.
