Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 将变量从配置文件传递到装饰器_Typescript_Nestjs_Typescript Decorator_Class Validator - Fatal编程技术网

Typescript 将变量从配置文件传递到装饰器

Typescript 将变量从配置文件传递到装饰器,typescript,nestjs,typescript-decorator,class-validator,Typescript,Nestjs,Typescript Decorator,Class Validator,我想用NestJs、TypeORM和类验证器创建一个restapi。我的数据库实体有一个描述字段,当前最大长度为3000。使用TypeORM,代码是 @Entity() export class Location extends BaseEntity { @Column({ length: 3000 }) public description: string; } 当创建一个新实体时,我想使用类验证器验证最大长度的传入请求。问题可能是 export class AddLocationD

我想用NestJs、TypeORM和类验证器创建一个restapi。我的数据库实体有一个描述字段,当前最大长度为3000。使用TypeORM,代码是

@Entity()
export class Location extends BaseEntity {
  @Column({ length: 3000 })
  public description: string;
}
当创建一个新实体时,我想使用类验证器验证最大长度的传入请求。问题可能是

export class AddLocationDTO {
  @IsString()
  @MaxLength(3000)
  public description: string;
}
当更新该描述字段时,我还必须检查其他DTO中的最大长度。我有一个服务类,它保存了API的所有配置字段。假设这个服务类也可以提供最大长度的服务,有没有一种方法可以将变量传递给decorator


否则,当将长度从3000更改为2000时,我必须更改多个文件。

由于Typescript的限制,无法在装饰器中使用类似
@nestjs/config
ConfigService
的内容。话虽如此,您也没有理由不能创建一个常量,将其分配给
process.env
中的值,然后在装饰器中使用该常量。所以在你的情况下,你可以

//constants.ts
//您可能需要导入`dotenv`并运行config(),但这可能取决于服务器的启动方式
导出常量字段长度=process.env.FIELD\u长度
//location.entity.ts
@实体()
导出类位置扩展BaseEntity{
@列({length:fieldLength})
公共描述:字符串;
}
//add-location.dto.ts
导出类AddLocationDTO{
@IsString()
@最大长度(字段长度)
公共描述:字符串;
}