nestjs / TypeOrm database transaction

后端 未结 4 1539
遥遥无期
遥遥无期 2021-01-12 13:45

Assuming we have 2 services, A and B. Service A has a function doing the following:

  1. Validate the data
  2. Call a service B function, that makes changes to
4条回答
  •  -上瘾入骨i
    2021-01-12 13:51

    Here is how I solved it since I needed to use a pessimistic lock.

    I feel it is the "Nest" way of doing things as you can simply ask NestJS to inject an instance of a Typeorm Connection and you're good to go.

    @Injectable()
    class MyService {
      // 1. Inject the Typeorm Connection
      constructor(@InjectConnection() private connection: Connection) { }
    
      async findById(id: number): Promise {
        return new Promise(resolve => {
          // 2. Do your business logic
          this.connection.transaction(async entityManager => {
            resolve(
              await entityManager.findOne(Thing, id, {
                lock: { mode: 'pessimistic_write' },
              }),
            );
          });
        });
      }
    }
    

    Simply place whatever other logic you need inside the .transaction block and you're good to go.

    NOTE: You MUST use the entityManager provided by the .transaction method or else it will not work.

提交回复
热议问题