【问题标题】:NestJS+TypeORM - Access Repo from Subscriber (trying to imitate Triggers)NestJS+TypeORM - 从订阅者访问回购(试图模仿触发器)
【发布时间】:2020-11-16 16:11:51
【问题描述】:

我正在使用 NestJS 进行我的第一个项目,我有点困惑。

我有 2 个实体:AccountTransaction

我应该如何实现一种方法来更新 Account.balanceTransactions 中的更改(创建、更新、删除)

看起来我应该创建一个TransactionsSubscriber,但我似乎无法访问数据库连接。

订阅者被加载到ormconfig.json

我觉得我错过了一些明显的东西,但我已经被困在那里太久了。请有人帮帮我。

@EventSubscriber()
export class TransactionsSubscriber
  implements EntitySubscriberInterface<TransactionEntity> {
  constructor(
    @InjectConnection('Account') readonly connection: Connection,
    @InjectRepository(TransactionEntity) transactionsRepo: Repository<TransactionEntity>,
    // @InjectEventEmitter() private emitter: AppEventEmitter,
    @Inject(REQUEST) private readonly request,
  ) {
    // connection.subscribers.push(this);
    console.log(
      typeof connection, // <=== ** here it returns me undefined **
      typeof transactionsRepo // and here too
      //, typeof emitter
    );
  }

  /**
   * Indicates that this subscriber only listen to TransactionEntity events.
   */
  listenTo() {
    return TransactionEntity;
  }

  afterInsert(event: InsertEvent<TransactionEntity>) {
    console.log(`After Transaction INSERTED: `, event.entity);
  }
}

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    您不能在订阅构造函数中使用@Inject(REQUEST) private readonly request 作为subscribers can not be request-scoped
    您不应该使用ormconfig.json 文件来绑定您的订阅者。 将订阅者添加到模块提供者:

    @Module({
      imports: [TypeOrmModule.forFeature([User])],
      providers: [UsersService, TransactionsSubscriber],
      controllers: [UsersController],
    })
    export class UsersModule {}
    

    【讨论】:

    • 所以没有办法在订阅者内部获取请求上下文?
    猜你喜欢
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多