我想用NestJs,TypeORM和class-validator创建一个REST API。我的数据库实体有一个描述字段,当前最大长度为3000。使用TypeORM,代码为
@Entity()
export class Location extends BaseEntity {
@Column({ length: 3000 })
public description: string;
}
创建新实体时,我想使用class-validator验证传入请求的最大长度。可能是
export class AddLocationDTO {
@IsString()
@MaxLength(3000)
public description: string;
}
更新该说明字段时,我也必须检查其他DTO中的最大长度。我有一个服务类,其中包含API的所有配置字段。假设此服务类也可以提供最大长度,是否有办法将变量传递给装饰器?
否则,将长度从3000更改为2000时,我必须更改多个文件。
答案 0 :(得分:2)
由于Typescript的限制,无法在装饰器中使用@nestjs/config
ConfigService
之类的东西。话虽如此,您也没有理由不能创建从process.env
分配给值的常量,然后在装饰器中使用该常量。因此,就您而言,您可以
// constants.ts
// you may need to import `dotenv` and run config(), but that could depend on how the server starts up
export const fieldLength = process.env.FIELD_LENGTH
// location.entity.ts
@Entity()
export class Location extends BaseEntity {
@Column({ length: fieldLength })
public description: string;
}
// add-location.dto.ts
export class AddLocationDTO {
@IsString()
@MaxLength(fieldLength)
public description: string;
}