Que*_*n3r 2 typescript typescript-decorator class-validator nestjs
我想用 NestJs、TypeORM 和类验证器创建一个 REST API。我的数据库实体有一个当前最大长度为 3000 的描述字段。使用 TypeORM,代码是
@Entity()
export class Location extends BaseEntity {
@Column({ length: 3000 })
public description: string;
}
Run Code Online (Sandbox Code Playgroud)
创建新实体时,我想使用类验证器验证该最大长度的传入请求。可能是
export class AddLocationDTO {
@IsString()
@MaxLength(3000)
public description: string;
}
Run Code Online (Sandbox Code Playgroud)
更新该描述字段时,我也必须检查其他 DTO 中的最大长度。我有一个服务类,其中包含 API 的所有配置字段。假设这个服务类也可以提供最大长度,有没有办法将变量传递给装饰器?
否则,当将长度从 3000 更改为 2000 时,我必须更改多个文件。
@nestjs/config
ConfigService
由于 Typescript 的限制,无法在装饰器中使用类似的东西。话虽如此,也没有理由不能创建分配给值的常量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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1218 次 |
最近记录: |