Skip to content

Commit

Permalink
refactor(be): refactoring exception handling logic (#239)
Browse files Browse the repository at this point in the history
refactor: refactoring exception handling logic
  • Loading branch information
yu-yj215 authored Dec 2, 2024
1 parent 5f4100d commit 3fd317f
Show file tree
Hide file tree
Showing 11 changed files with 245 additions and 421 deletions.
55 changes: 23 additions & 32 deletions apps/server/src/chats/chats.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,40 @@ import { Injectable } from '@nestjs/common';

import { ChatSaveDto } from './chats.service';

import { DatabaseException } from '@common/exceptions/resource.exception';
import { PrismaService } from '@prisma-alias/prisma.service';

@Injectable()
export class ChatsRepository {
constructor(private readonly prisma: PrismaService) {}
async save({ sessionId, token, body }: ChatSaveDto) {
try {
return await this.prisma.chatting.create({
data: { sessionId, createUserToken: token, body },
include: {
createUserTokenEntity: {
select: {
user: true,
},
return await this.prisma.chatting.create({
data: { sessionId, createUserToken: token, body },
include: {
createUserTokenEntity: {
select: {
user: true,
},
},
});
} catch (error) {
throw DatabaseException.create('chat');
}
},
});
}
async getChatsForInfiniteScroll(sessionId: string, count: number, chatId?: number) {
try {
return await this.prisma.chatting.findMany({
where: {
sessionId,
...(chatId && { chattingId: { lt: chatId } }),
},
include: {
createUserTokenEntity: {
include: {
user: true,
},
return await this.prisma.chatting.findMany({
where: {
sessionId,
...(chatId && { chattingId: { lt: chatId } }),
},
include: {
createUserTokenEntity: {
include: {
user: true,
},
},
orderBy: {
chattingId: 'desc',
},
take: count,
});
} catch (error) {
throw new Error('Error retrieving chats from database');
}
},
orderBy: {
chattingId: 'desc',
},
take: count,
});
}
}
28 changes: 0 additions & 28 deletions apps/server/src/common/exceptions/resource.exception.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,7 @@
import { HttpException, HttpStatus } from '@nestjs/common';

export class ResourceNotFoundException extends HttpException {
constructor(resource: string) {
super(`${resource}를 찾을 수 없습니다.`, HttpStatus.NOT_FOUND);
}
}

export class ResourceConflictException extends HttpException {
constructor(message: string) {
super(message, HttpStatus.CONFLICT);
}
}

export class DatabaseException extends HttpException {
constructor(operation: string) {
super(`데이터베이스 ${operation} 중 오류가 발생했습니다`, HttpStatus.INTERNAL_SERVER_ERROR);
}

static create(entity: string) {
return new DatabaseException(`${entity} 생성`);
}

static read(entity: string) {
return new DatabaseException(`${entity} 조회`);
}

static update(entity: string) {
return new DatabaseException(`${entity} 수정`);
}

static delete(entity: string) {
return new DatabaseException(`${entity} 삭제`);
}
}
13 changes: 8 additions & 5 deletions apps/server/src/common/guards/session-token-validation.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ export class SessionTokenValidationGuard implements CanActivate {
private readonly sessionsAuthRepository: SessionsAuthRepository,
) {}

async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const sessionId = request.body?.sessionId || request.query?.sessionId || request.params?.sessionId;
const token = request.body?.token || request.query?.token;

async validateSessionToken(sessionId: string, token: string) {
if (!sessionId || !token) {
throw new ForbiddenException('세션 ID와 사용자 토큰이 필요합니다.');
}
Expand All @@ -33,7 +29,14 @@ export class SessionTokenValidationGuard implements CanActivate {
if (!userSessionToken || userSessionToken.sessionId !== sessionId) {
throw new ForbiddenException('해당 세션에 접근할 권한이 없습니다.');
}
}

async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const sessionId = request.body?.sessionId || request.query?.sessionId || request.params?.sessionId;
const token = request.body?.token || request.query?.token;

await this.validateSessionToken(sessionId, token);
return true;
}
}
Loading

0 comments on commit 3fd317f

Please sign in to comment.