typescript - 在NestJS中手动注册一个typeorm EventSubscriber,而不在配置文件中指定

标签 typescript nestjs typeorm typescript-decorator nestjs-config

在 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,
) {

enter image description here

关于typescript - 在NestJS中手动注册一个typeorm EventSubscriber,而不在配置文件中指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73435326/

相关文章:

javascript - Angular 重置下拉值 primeng

typescript - 如何使用 Jest 在 TypeORM 中 stub EntityManager 和 Connection

mysql - TypeORM with MySQL Error : Pool is closed. 调用数据库时测试卡住了

javascript - Angular 自定义指令范围未按预期更新

angular - 没有任何声明模块的类型文件是否有意义?

node.js - 输出到另一个目录时,如何在 Typescript 编译过程中包含 .html 文件

typescript - 使用 passport-jwt 在 nestJs 框架中进行角色验证

node.js - 在 NestJS CQRS 配方中处理 "Event Sourcing"的首选方式

swagger - NestJS 映射类型 - 嵌套对象

nestjs - 有没有一种方法可以使用 Group By 和 Count with Type Orm Repository