Aay*_*eja 7 postgresql node.js typescript nestjs
我无法在 NestJS 中确定如何使用类验证器(使用 PostgreSQL 作为数据库)将某些字段标记为 NULLABLE 或 NOT NULLABLE。请参阅下面的示例。
考虑以下实体,其中货币为NOT NULL DEFAULT字段,数量为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
}
Run Code Online (Sandbox Code Playgroud)
在POST /product请求中,货币字段被标记@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;
}
Run Code Online (Sandbox Code Playgroud)
在PATCH /product请求中,所有字段都标记为@IsOptionalusing PartialType。
import { PartialType } from '@nestjs/mapped-types';
import { CreateProductDto } from './create-product.dto';
export class PatchProductDto extends PartialType(CreateProductDto) {}
Run Code Online (Sandbox Code Playgroud)
使用上述验证逻辑,我面临以下问题:
NOT NULL DEFAULT字段货币,@IsOptional理想情况下应该允许缺少值,但也允许null,这会导致内部服务器错误。@IsOptional,并且发送nullNOT NULL 字段 - name 的值会导致内部服务器错误。| 归档时间: |
|
| 查看次数: |
8784 次 |
| 最近记录: |