我无法在 NestJS 中确定如何使用类验证器(使用 PostgreSQL 作为数据库)将某些字段标记为 NULLABLE 或 NOT NULLABLE。请参阅下面的示例。
考虑以下实体,其中 currency 作为
NOT NULL DEFAULT
字段,quantity 作为 NULL
字段:
@Entity('product')
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column({type: 'int'})
price: number;
@Column({
type: 'enum',
enum: Currencies,
default: Currencies.USD
})
currency: Currencies; // NOT NULL DEFAULT
@Column({type: 'int', nullable: true})
quantity: number; // NULLABLE COLUMN
}
在
POST
/product 请求中,currency 字段被标记为 @IsOptional
以免除请求中不存在该字段的情况。
import { IsEnum, IsInt, IsOptional, IsString, Max, Min } from 'class-validator';
enum Currencies {
USD = 'USD',
INR = 'INR',
GBP = 'GBP',
EUR = 'EUR',
}
export class CreateProductDto {
@IsString()
readonly name: string;
@IsInt()
@Min(0)
readonly price: number;
@IsOptional()
@IsString()
@IsEnum(Currencies)
readonly currency: Currencies;
@IsOptional()
@IsInt()
@Min(0)
@Max(100)
readonly quantity: number;
}
在
PATCH
/product 请求中,所有字段均使用 @IsOptional
标记为 PartialType
。
import { PartialType } from '@nestjs/mapped-types';
import { CreateProductDto } from './create-product.dto';
export class PatchProductDto extends PartialType(CreateProductDto) {}
使用上述验证逻辑,我面临以下问题:
NOT NULL DEFAULT
字段 - currency,理想情况下,@IsOptional
应该允许缺失值,但也允许 null
,这会导致 内部服务器错误。@IsOptional
,并且发送 null
作为 NOT NULL 字段的值 - 名称,会导致内部服务器错误。您可能需要创建自定义验证类或装饰器:
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';
@ValidatorConstraint({ name: 'justNotNull', async: false })
export class JusrNotNull implements ValidatorConstraintInterface {
validate(text: string, args: ValidationArguments) {
return typeof text === 'string' || text === undefined; // for async validations you must return a Promise<boolean> here
}
defaultMessage(args: ValidationArguments) {
// here you can provide default error message if validation failed
return 'Your error message!';
}
}