NestJS+TypeORM - 从订阅者访问存储库(尝试模仿触发器)

标签 nestjs typeorm

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

我有 2 个实体:AccountTransaction

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

看起来我应该创建一个 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);
  }
}

最佳答案

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

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

关于NestJS+TypeORM - 从订阅者访问存储库(尝试模仿触发器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64218541/

相关文章:

node.js - 在 Nest.js 中访问 Stripe webhook 的原始主体

typescript - Typeorm 迁移未正确检测更改

javascript - 如何使用 nestfastify 编写来自 nestjs 异常过滤器的响应

javascript - 无法跨一对多查询属性 NestJS 和 TypeORM

nestjs - TypeORM:当我们有一对多和多对一关系时加入

node.js - NestJS 中同一 Controller (路由别名)的两个端点

node.js - 使用 FileInterceptor 上传文件时如何在 NestJs 中返回自定义状态代码?

node.js - 如何从 Controller JSON 返回的实体字段中排除。 NestJS + Typeorm

node.js - 使用 lerna 类型-graphql --- 错误 : Cannot determine GraphQL output type for id

mongodb - 无法读取未定义的属性 'prototype' - 使用 typeorm 和 mongoDB 的 Nestjs