我有一个实体Audit
,类似于在Nestjs应用中使用mongodb的typeorm的实体:
@Entity()
export class Audit {
@Column()
createdBy: string;
@BeforeInsert()
setAudit() {
this.createdBy = ???
}
}
@Entity()
export class Post extends Audit {
@Column()
title: string;
...
}
我的其他实体扩展了Audit
,在我的应用程序中,我使用jwt来验证用户身份。
问题是,当我要保存实体时,我不知道如何使用@BeforeInsert钩子来设置createdBy ...
我知道我们正在请求用户,但我不知道将用户带入setAudit
方法的正确方法是什么?
答案 0 :(得分:0)
您不能直接从TypeORM实体内部访问请求,因为它们位于单独的上下文中。您可以改为通过服务填充createdBy字段。
@Injectable()
class DataService {
// ...
async create({ request, user }): Promise<any> {
await this.repository.create({...request.body, createdBy: user.id });
}
// ...
}
另一种解决方案是创建一个可用于每个实体的通用服务,然后在该服务内填充createdBy属性。
/*
* DataService
? Service to be able to fetch any kind of TypeORM entity from the controllers
? or another services.
*/
@Injectable()
export class DataService {
/*
* _.getRepository
? Method to get a repository by having only the type of an entity.
* @param type The type of the entity
* @returns a repository of the specified entity.
*/
private getRepository<T>(type: new () => T) {
return getRepository(type)
}
/*
* _.save
? A method to save an entity regarding its entity type.
* @param type the type of the entity
* @param model the model to save. It should have an ID.
* @param user the user creating this entity
* @returns a DeepPartial object representing the edited or created object.
*/
public save<T extends Audit>(type: new () => T, model: DeepPartial<T>, user: User): Promise<DeepPartial<T> & T> {
const repository: Repository<T> = this.getRepository(type);
return repository.save({...model, createdBy: user.id});
}
}
然后,您将可以执行以下操作……
// ...
@Post('create')
@UseInterceptor(FillUser)
public async create(@Body() body:any, @Req() request:any) {
const { user } = request.session.user // <--- Just for example.
return await this.service.create(Post, body, user)
}
// ...