3

我想用 NestJs、TypeORM 和类验证器创建一个 REST API。我的数据库实体有一个描述字段,当前最大长度为 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 配置字段。假设这个服务类也可以提供最大长度,有没有办法可以将变量传递给装饰器?

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

4

1 回答 1

10

@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;
}

于 2020-04-16T14:04:16.400 回答