在 NestJS 中,我扩展了 EntitySubscriberInterface 类来创建通用的 EventSubscriber。
我的目标是每次在数据库中插入某些内容时捕获所有 typeorm 存储库事件“beforeInsert”(应该为所有实体触发)。
该代码之所以有效,是因为该文件保存在 NestJS 中 src 文件夹内的文件夹之一中,并且其路径在 NestJS 配置文件中指定;这样做时,订阅者文件会自动加载。
我的目标是将此文件移动到 npm 包中,以便我可以从 NestJS 应用程序的主逻辑中提取它,然后在需要时初始化它,执行诸如“new ValidatorSubscriber()”之类的操作;
是否可以?因为到目前为止我所有的尝试都失败了。
我尝试在 app.module.ts 中初始化我的 ValidatorSubscriber 类,并且构造函数被正确调用,但订阅者无法工作。
有什么想法吗?
import { EntitySubscriberInterface, EventSubscriber, InsertEvent } from 'typeorm';
@EventSubscriber()
export class ValidatorSubscriber<T> implements EntitySubscriberInterface<T> {
private entitiesMap = new Map();
constructor() {
console.log('EventSubscriber constructor')
import('../db/entities') // get all entities
.then((allEntities: any) => {
for (const prop in allEntities) {
this.entitiesMap.set(prop, allEntities[prop])
}
console.log(allEntities)
});
}
/**
* Called before post insertion.
*/
async beforeInsert(event: InsertEvent<any>): Promise<void> {
console.log(`BEFORE INSERTION, ${JSON.stringify(event.entity)}`)
}
}
最佳答案
如果有人需要它,我设法找到了解决方案。
我结合了this stackoverflow post的答案答案 provided here作者:fwoelffel(参见答案的屏幕截图)。
请记住,InjectConnection 已被弃用,我使用了它:
constructor(
@Inject(Connection) readonly connection: Connection,
) {
关于typescript - 在NestJS中手动注册一个typeorm EventSubscriber,而不在配置文件中指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73435326/