首页 > 解决方案 > Nest.js + TypeORM + OpenApi 中虚拟(计算)列的最佳实践

问题描述

我有一个实体(图像),它具有这样的计算属性(图像路径):

@Entity()
export class Image extends BaseEntity {
  @PrimaryGeneratedColumn()
  @IsInt()
  id: number

  @Column({ type: 'varchar', length: 255, unique: true })
  @IsString()
  @IsNotEmpty()
  uid: string

  protected mainPath: string

  @AfterLoad()
  @AfterInsert()
  @AfterUpdate()
  generateMainPath(): void {
    this.mainPath = Math.floor(this.id / 10000) + '/' + Math.floor(this.id / 100) + '/' + this.uid
  }
}

我使用 mainPath 将图像存储在后端文件系统中,并将其发送到前端以构建 img src 路径。mainPath成功生成并发送给客户端。

问题是前端使用 swagger (nswag openapi2tsclient) 生成的基于 openApi 模式的 typescript 文件,由 Nest.JS 生成。生成的文件中没有interface的mainPath属性。IImage是否可以以某种方式声明它,以便在客户端上定义它并填充来自 ajax 响应的提供值?

PS1。试图装饰mainPath-@ApiProperty({ type: String })它没有帮助。

PS2。尝试使用@Column({ type: virtual }),但后端随后发出警告,表明 MySQL 不支持这种类型。

PS3。它似乎mainPath应该在前端声明为一些通常的未计算属性,因为它将预先填充来自后端的数据(它不会在前端计算)。

PS4。可能的方法似乎是将裸模型用于数据库和ExtendedImage具有mainPath在构造函数中计算的属性(如果未提供)的类。这是最佳实践吗?

标签: typescriptswaggernestjsopenapitypeorm

解决方案


通过使用来自class-validator. 我不知道它为什么起作用:

@Entity()
export class Image extends BaseEntity {
  @PrimaryGeneratedColumn()
  @IsInt()
  id: number

  @Column({ type: 'varchar', length: 255, unique: true })
  @IsString()
  @IsNotEmpty()
  uid: string

  @IsString()
  @IsOptional()
  protected mainPath: string

  @AfterLoad()
  @AfterInsert()
  @AfterUpdate()
  generateMainPath(): void {
    this.mainPath = Math.floor(this.id / 10000) + '/' + Math.floor(this.id / 100) + '/' + this.uid
  }

推荐阅读