我有一个实体(图像),它具有这样的计算属性(图像路径):
@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) 生成的 typescript 文件建立在 openApi 模式之上,由 Nest.JS 生成。生成的文件中没有 IImage
接口(interface)的 mainPath
属性。是否可以以某种方式声明它以便在客户端定义它并填充来自 ajax 响应的提供值?
附注 1。试图用 @ApiProperty({ type: String })
装饰 mainPath
- 它没有帮助。
附注 2。尝试使用 @Column({ type: virtual })
但后端会发出警告,指出 MySQL 不支持此类型。
附注 3。似乎 mainPath
应该在前端声明为一些通常的非计算属性,因为它会预先填充来自后端的数据(它不会在前端计算) .
附注 4。可能的方法似乎是对数据库和 ExtendedImage
类使用裸模型,该类具有在构造函数中计算的 mainPath
属性(如果未提供)。这是最佳做法吗?
最佳答案
通过使用 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
}
关于typescript - Nest.js + TypeORM + OpenApi 中虚拟(计算)列的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64985390/