From 17ba8b1c7db862e0c251e13d0e6355e9cbed1e44 Mon Sep 17 00:00:00 2001 From: Phuoc Nguyen Date: Fri, 23 May 2025 10:20:25 +0700 Subject: [PATCH] transaction --- .../authentication.controller.ts | 1 + src/users/user.service.ts | 38 +++++++++++++++++-- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/authentication/authentication.controller.ts b/src/authentication/authentication.controller.ts index df36392..e7658db 100644 --- a/src/authentication/authentication.controller.ts +++ b/src/authentication/authentication.controller.ts @@ -18,6 +18,7 @@ import JwtAuthenticationGuard from './jwt-authentication.guard'; import {ApiBody} from '@nestjs/swagger'; import LogInDto from './dto/logIn.dto'; import {UsersService} from 'src/users/user.service'; +import JwtRefreshGuard from "./jwtRefreshGuard.guard"; @Controller('authentication') @UseInterceptors(ClassSerializerInterceptor) diff --git a/src/users/user.service.ts b/src/users/user.service.ts index 0328168..139f105 100644 --- a/src/users/user.service.ts +++ b/src/users/user.service.ts @@ -1,6 +1,6 @@ -import {HttpException, HttpStatus, Injectable} from '@nestjs/common'; +import {HttpException, HttpStatus, Injectable, InternalServerErrorException} from '@nestjs/common'; import {InjectRepository} from '@nestjs/typeorm'; -import {Repository} from 'typeorm'; +import {Repository, Connection} from 'typeorm'; import User from './entities/user.entity'; import CreateUserDto from './dto/createUser.dto'; import * as bcrypt from 'bcrypt'; @@ -11,7 +11,8 @@ export class UsersService { constructor( @InjectRepository(User) private usersRepository: Repository, - private readonly filesService: FilesService + private readonly filesService: FilesService, + private connection: Connection, ) { } @@ -57,12 +58,38 @@ export class UsersService { return avatar; } + async deleteAvatar(userId: number) { + const queryRunner = this.connection.createQueryRunner(); + + const user = await this.getById(userId); + const fileId = user.avatar?.id; + if (fileId) { + await queryRunner.connect(); + await queryRunner.startTransaction(); + + try { + await queryRunner.manager.update(User, userId, { + ...user, + avatar: null + }); + await this.filesService.deletePublicFileWithQueryRunner(fileId, queryRunner); + await queryRunner.commitTransaction(); + } catch (error) { + await queryRunner.rollbackTransaction(); + throw new InternalServerErrorException(); + } finally { + await queryRunner.release(); + } + + } + } + async create(userData: CreateUserDto) { const newUser = this.usersRepository.create(userData); await this.usersRepository.save(newUser); return newUser; } - + //region token async setCurrentRefreshToken(refreshToken: string, userId: number) { const currentHashedRefreshToken = await bcrypt.hash(refreshToken, 10); await this.usersRepository.update(userId, { @@ -75,4 +102,7 @@ export class UsersService { currentHashedRefreshToken: null, }); } + //endregion + + }