我正在使用 NestJS 进行第一个项目,但我有点困惑。
我有 2 个实体:Account
和 Transaction
我应该如何实现一种方法来根据交易
中的更改(创建、更新、删除)更新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/