arve
arve

Reputation: 801

how to return a newly created object when using sequelize transcation?

I have a following function, which works, when passed a new user data . it saves the object and the child object into the mysql table successfully. but how do i return the object back , once saved to the database, given i'm using sequelize transaction.

static async add(user) {
    let transaction; 
      try {
          // get transaction
        transaction = await models.sequelize.transaction();

        //  *****how to return the newly created user *****************************************

        models.User.create(user).then(newUser => {
          const id = newUser.id;

           //save address 
          if(user.address){

              address.userId = id;
              models.Address.create(address); 

          }
        }).catch(error => {
          throw error;
        }); 

        await transaction.commit();

      } catch (error) {
          console.log(error); 
            // Rollback transaction 
          if (transaction) await transaction.rollback();
          throw error;
      }
    }

Upvotes: 1

Views: 8051

Answers (1)

Anatoly
Anatoly

Reputation: 22793

Try to create an auto-transaction, use await and indicate transaction in models's create functions:

static async add(user) {
      try {
        const createdUser = await models.sequelize.transaction(transaction => {
          const newUser = await models.User.create(user, { transaction })
           //save address 
          if(user.address){
            address.userId = newUser.id;
            await models.Address.create(address, { transaction }); 
          }
          return newUser;
        });
        // if you are here it means transaction already commited
        return createdUser;
      } catch (error) {
          // if you are here it means transaction already rolled back
          console.log(error); 
          throw error;
      }
    }

Upvotes: 3

Related Questions