onwuvic / nest-blog-api

Blog Web API with NestJs, Postgres, and Sequelize ORM

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to add transaction

ThanhDeveloper opened this issue · 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 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

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;
    }
  }