nest-blog-api icon indicating copy to clipboard operation
nest-blog-api copied to clipboard

How to add transaction

Open ThanhDeveloper opened this issue 3 years ago • 2 comments

I tried to add transaction to this repo. Can you guide how to use transaction. I'd love to see how you use it at create user. Thanks

ThanhDeveloper avatar Apr 08 '22 12:04 ThanhDeveloper

@ThanhDeveloper I'm sorry for responding this late. I have been away from his repo and I just saw this.

I have a project where I used the transaction

async create(user: UserDto): Promise<any> {
   // start a transaction
   const transaction = await this.sequelize.transaction();
   try  {
      // create a user
      const createdUser = await this.userRepository.create<User>(user, { transaction });
      
      // once user is created get the user Id
      // create a profile with user id
      await createdUser.$create('profile', createdUser, { transaction });
      
      // await this.profileService.create(createdUser.id, transaction);

      await transaction.commit();
      // find the user and return
      const newUser = await this.findUserById(createdUser.id);

      return newUser; 
   } catch (error) {
       await transaction.rollback();
       throw new InternalServerErrorException('Error creating user account. Try again later');
   }  
 }

Here is a link to the repo Link

onwuvic avatar Sep 23 '22 19:09 onwuvic

Tks for your response. But I resovled it a long time ago. Here is my code:

public async register(user) {
    let transaction;
    try {
      transaction = await this.sequelize.transaction();

      const userExist = await this.userService.findOneByUsername(user.username);
      if (userExist) {
        throw new InvalidArgumentException('This username already exist');
      }

      // hash the password
      const pass = await AuthService.hashPassword(user.password);

      // create the user
      const newUser = await this.userService.create({
        ...user,
        password: pass,
      });
      // tslint:disable-next-line: no-string-literal
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const { password, ...result } = newUser['dataValues'];

      // generate token
      const token = await this.generateToken(result);

      await transaction.commit();

      // return the user and the token
      return {
        id: result.id,
        username: result.username,
        message: 'Register success',
        token,
      };
    } catch (error) {
      if (transaction) {
        await transaction.rollback();
      }
      throw error;
    }
  }

ThanhDeveloper avatar Sep 24 '22 02:09 ThanhDeveloper