Search code examples
node.jspostgresqltransactionsnestjstypeorm

how to create and edit in the single typeORM transaction


In my nestjs api I am going to create quiz with single transaction

Quiz Entity:

  • quiz_id //autogenerated
  • title //from input
  • questions //empty array of questions

then i want to create, save and add to question array every question,

my createQuestion has quiz_id argument because in createQuestion i am setting relation between quiz and questions.

is it possible to create first quiz with empty questions array for getting only quiz_id and then update this quiz in the single transaction?


Solution

  • it is indeed possible by using an EntityManager

    first thing you'll need to inject the entity manager in the service constructor:

      constructor(@InjectEntityManager() private readonly entityManager: EntityManager) {}
    

    after that you create a transaction session using entityManager as such

    await this.entityManager.transaction(async (em) => {
      const quiz = await em.save(quiz); // insert the quiz entity to DB
      quiz.addQuestions([q1, q2, q3]); // add question entity objects, assuming you have a method encapsulation for this (addQuestions)
      
      await em.save(quiz); // update the quiz DB entry with questions - cascade must be set on the entity
    
      // you can also fetch the quiz entity from the DB whilst in transaction as well by using 'em'
    });
    

    main takeaway is to fetch/save the data with em once you open a transaction session