我使用BaseEntity对TypeOrm进行了简单的扩展,在执行CRUD操作时,我希望强制从请求中获得一些属性值。
import {
Column,
BaseEntity,
PrimaryGeneratedColumn,
BeforeInsert,
BeforeUpdate
} from "typeorm";
import { IsOptional, IsNumber, IsDate, IsString } from "class-validator";
export class CrudEntity extends BaseEntity {
@PrimaryGeneratedColumn()
@IsOptional()
@IsNumber()
id?: number;
@Column({ nullable: true, default: null })
@IsString()
@IsOptional()
scope?: string;
@Column({ nullable: true, default: null })
@IsNumber()
@IsOptional()
client?: number;
@Column({ nullable: true, default: null })
@IsNumber()
@IsOptional()
user?: number;
@Column({ type: "timestamp", default: () => "CURRENT_TIMESTAMP" })
@IsDate()
@IsOptional()
created?: Date;
@Column({ nullable: true, default: null })
@IsNumber()
@IsOptional()
createdBy?: number;
@Column({ type: "timestamp", nullable: true, default: null })
@IsDate()
@IsOptional()
modified?: Date;
@Column({ nullable: true, default: null })
@IsNumber()
@IsOptional()
modifiedBy?: number;
@BeforeInsert()
public beforeInsert() {
this.setClient();
this.created = new Date();
// @TODO Get info from JWT
this.createdBy = null;
}
@BeforeUpdate()
public beforeUpdate() {
this.setClient();
this.modified = new Date();
// @TODO Get info from JWT
this.modifiedBy = null;
}
public setClient() {
// @TODO Get info from JWT
this.scope = null;
this.client = null;
}
}
我需要一种方法来检索在请求头中发送的已解码的JWT令牌,以便保存谁在什么时间插入或更新了什么。
我读过关于请求作用域、注入等的文章。我还没能找到一个简单的解决方案来解决一个其他人在编写NestJ后端服务时肯定会遇到的简单问题。
任何帮助都是非常感谢的。
发布于 2022-08-05 09:25:34
在我的例子中,没有触发@BeforeInsert
和@BeforeUpdate
,因为我将DTO实例传递给我的服务。
如果您希望触发它们,则必须使用plainToClass(CrudEntity, dto)
在其最终结果(这里是它的plainToClass(CrudEntity, dto)
)中转换它。当您的DTO包含与最终实体类不同的数据类型时,可能会很烦人。
https://stackoverflow.com/questions/70865205
复制相似问题