nestjs / TypeOrm database transaction

后端 未结 4 1542
遥遥无期
遥遥无期 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条回答
  • 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<Thing> {
        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.

    0 讨论(0)
  • 2021-01-12 13:51

    In this case, you have to use the same transaction manager for both database operations. Unfortunately, I do not have an example repository, but I have found a potential solution using Continuation Local Storage (CLS) in Node:

    https://github.com/typeorm/typeorm/issues/1895

    This applies to Express.js, but you can create an instance of TransactionManager (for example, in a nest middleware) and store it per each request context. You then will be able to re-use this transactional manager across your service method calls, provided they are annotated with the @Transaction decorator implementation in the link above.

    If there are no errors in your function chain, the transaction manager will commit all the changes made. Otherwise, the manager will roll back any changes.

    Hope this helps!

    0 讨论(0)
  • 2021-01-12 13:58

    typeorm-transactional-cls-hooked uses CLS (Continuation Local Storage) to handle and propagate transactions between different repositories and service methods.

    @Injectable()
    export class PostService {
      constructor(
        private readonly authorRepository: AuthorRepository,
        private readonly postRepository: PostRepository,
      ) {}
    
      @Transactional() // will open a transaction if one doesn't already exist
      async createPost(authorUsername: string, message: string): Promise<Post> {
        const author = await this.authorRepository.create({ username: authorUsername });
        return this.postRepository.save({ message, author_id: author.id });
      }
    }
    
    0 讨论(0)
  • Many solutions are available, they should all be based on SQL transaction management.

    Personally I feel that the simplest way to achieve that is to use the same EntityManager instance when you execute code on your database. Then you can use something like:

    getConnection().transaction(entityManager -> {
        service1.doStuff1(entityManager);
        service2.doStuff2(entityManager);
    });
    

    You can spawn a QueryRunner from an EntityManager instance that will be wrapped in the same transaction in case you execute raw SQL outside ORM operations. You need also to spawn Repository instances from EntityManager as well or they will execute code outside the main transaction.

    0 讨论(0)
提交回复
热议问题