nestjs-class-validator-plugin
v0.1.2
Published
Nest CLI TypeScript transformer plugin that auto-injects class-validator decorators based on DTO property types and optionality (TypeORM friendly)
Maintainers
Readme
nestjs-class-validator-plugin
Nest CLI TypeScript transformer plugin that auto-injects class-validator decorators based on DTO property types and optionality.
Installation
Install as a dev dependency:
npm install --save-dev nestjs-class-validator-pluginUsage
Add the plugin to your nest-cli.json or TypeScript compiler options used by Nest CLI. Example nest-cli.json:
{
"compilerOptions": {
"plugins": [
{
"name": "nestjs-class-validator-plugin",
"options": {
"include": ["src/**/*.dto.ts"],
"exclude": ["**/*.entity.ts"],
"mode": "missing",
"verbose": true
}
}
]
}
}插件选项说明
include(string[])- 仅处理文件路径包含这些子串的 DTO 文件(如 ["dto", "dtos"])。支持简单通配符(如
src/**/*.dto.ts)。 - 例如:
include: ["src/**/*.dto.ts"]只处理 DTO 文件。
- 仅处理文件路径包含这些子串的 DTO 文件(如 ["dto", "dtos"])。支持简单通配符(如
exclude(string[])- 排除文件路径包含这些子串的文件(如 ["entity"])。
- 例如:
exclude: ["**/*.entity.ts"]排除所有 entity 文件。
mode("all" | "missing")- "missing"(默认):仅为未显式声明 class-validator 装饰器的属性自动注入。
- "all":无论属性是否已有装饰器,均自动注入(可能导致重复)。
verbose(boolean)- 开启后,编译时在控制台输出每个文件/属性将自动注入哪些装饰器,便于调试和 CI 验证。
- 例如:
validator-cli-plugin: diagnostics for d:/path/to/src/users/dto/create-user.dto.ts: - d:/path/to/src/users/dto/create-user.dto.ts -> names: will add [IsOptional, IsArray, IsString] - d:/path/to/src/users/dto/create-user.dto.ts -> addresses: will add [IsNotEmpty, IsArray, ValidateNested, Type]
对象数组自动注解示例
假设 DTO 如下:
export class AddressDto {
street: string;
}
export class CreateUserDto {
names?: string[]; // 自动注入 IsOptional, IsArray, IsString({ each: true })
addresses: AddressDto[]; // 自动注入 IsNotEmpty, IsArray, ValidateNested({ each: true }), Type(() => AddressDto)
}编译后会自动生成如下装饰器:
import { IsOptional, IsArray, IsString, IsNotEmpty, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
...existing code...
export class CreateUserDto {
@IsOptional()
@IsArray()
@IsString({ each: true })
names;
@IsNotEmpty()
@IsArray()
@ValidateNested({ each: true })
@Type(() => AddressDto)
addresses;
}Example
Given a DTO property name?: string, the plugin will add IsOptional and IsString automatically (when configured).
License
MIT
