如何将 PUT 端点迁移到基于命令的应用程序(事件源)

问题描述 投票:0回答:1

我几乎完成了使用 NestJS 的 CQRS 模块实现事件源,但现在有一些我不知道如何处理。 目前,我有 cron 作业,每小时将事务发送到我的 PUT /transactions 端点。有效负载是这样的:

{
    "status": "pending",
    "amount": 10000,
    "uid": "test123",
    "transaction_id": "test-transaction1234",
}

当交易发送到端点时,我还不知道哪些字段发生了变化。 我有四个可能的命令:

CreateTransactionCommand
UpdateAmountCommand
ApproveTransactionCommand
DeclineTransactionCommand
。两个命令可以“同时”发生,例如 UpdateAdmount,然后是 ApproveTransaction。第一个应该首先发生。

我该如何处理?我正在考虑这样的事情,有什么好的解决方案吗?

  @Put()
  async createOrUpdate(@Body() dto: Transaction) {
    try {
      await this.transactionsService.createTransaction(dto);
    } catch (e) {
      if (typeof e == ExistingTransactionError) console.error(e);
      else throw e;
    }
    try {
      await this.transactionsService.updateTransactionAmount(dto);
    } catch (e) {}
    if (dto.status === 'approved')
      await this.transactionsService.approveTransaction(dto);
    if (dto.status === 'declined')
      await this.transactionsService.declineTransaction(dto);
  }
nestjs cqrs event-sourcing
1个回答
0
投票

好吧,我只是做了一个 PUT 端点,并且由于聚合根的强大功能,很容易知道我可以执行哪个命令。

  @Put()
  async createOrUpdate(@Body() dto: TransactionEventDto) {
    try {
      return await this.transactionsService.createTransaction({
        ...dto.payload,
        status: 'pending',
      });
    } catch (e) {
      if (!(e instanceof TransactionAlreadyCreatedError))
        throw new HttpException(e.message, HttpStatus.BAD_REQUEST, e);
    }
    try {
      const { transaction_id, amount, status } = dto.payload;
      await this.transactionsService.updateTransactionAmount(
        transaction_id,
        amount,
      );
      if (status === 'approved') {
        return await this.transactionsService.approveTransaction(
          transaction_id,
        );
      }
      if (status === 'declined') {
        return await this.transactionsService.declineTransaction(
          transaction_id,
        );
      }
      return;
    } catch (e) {
      throw new HttpException(e.message, HttpStatus.BAD_REQUEST, e);
    }
  }

如果顺序很重要,只需使用 Promise 的“顺序方式”(即链中等待)

© www.soinside.com 2019 - 2024. All rights reserved.