typescript - 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
在构造函数中计算的属性(如果未提供)的类。这是最佳实践吗?
解决方案
通过使用来自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
}
推荐阅读
- ios - X 轴动作奇怪 - 图表 iOS
- java - 快速关闭等效的java lambda
- r - 如何在 R 中的 Plotly 中使直方图条具有不同的颜色
- laravel - 根据子存在和列值过滤多对多关系
- get - 使用 API 获取 Dailymotion 视频与 Dailymotion 本身完全相同的顺序
- jquery - 如何比较和匹配来自不同元素的字符串?
- python - Pandas 在同一个表中合并多个列,产生意外的输出
- regex - 正则表达式仅匹配关键字
- javascript - 仅选择javascript中的输入字段
- spring - Spring Cloud Kubernetes FeignClient 错误