From 3245c633eadc602d6c66b9294b391f65882e74f8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=EC=A1=B0=EB=8C=80=ED=9D=AC?= <joedaehui@ajou.ac.kr>
Date: Sat, 7 Dec 2024 18:07:30 +0900
Subject: [PATCH] =?UTF-8?q?refactor:=20=EC=B9=9C=EA=B5=AC=20=EC=9A=94?=
 =?UTF-8?q?=EC=B2=AD=20=EB=B3=B4=EB=82=B4=EA=B8=B0=20req=20=EC=88=98?=
 =?UTF-8?q?=EC=A0=95=20(#23)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 controllers/friendController.js | 168 +++++++++++++++++---------------
 services/friendService.js       |   2 +-
 2 files changed, 88 insertions(+), 82 deletions(-)

diff --git a/controllers/friendController.js b/controllers/friendController.js
index ce50caf..09cbf57 100644
--- a/controllers/friendController.js
+++ b/controllers/friendController.js
@@ -1,53 +1,59 @@
 const FriendService = require('../services/friendService');
 const { User } = require('../models');
+const performanceMonitor = require('../utils/performanceMonitor');
 
 class friendController {
-        /**
-         * 친구 요청 보내기
-         * 클라이언트는 userId와 요청을 보낼 사용자의 email을 전송
-         */
-        async sendFriendRequest(req, res, next) {
-            const { userId, email } = req.body;
-    
-            try {
+    /**
+     * 친구 요청 보내기
+     * 클라이언트는 userId와 요청을 보낼 사용자의 email을 전송
+     * POST /api/friend/request
+     * 
+     */
+    async sendFriendRequest(req, res) {
+        try {
+            return await performanceMonitor.measureAsync('sendFriendRequest', async () => {
+                const email  = req.body;
+                const userId = req.user.id;
 
                 if (!userId || !email) {
-                    return res.status(400).json({ message: 'userId와 email은 필수 입력 항목입니다.' });
+                    throw new Error('userId와 email은 필수 입력 항목입니다.');
                 }
-                // 친구 요청을 받을 사용자의 정보 조회 (서비스로 분리할지 생각)
-                const receiver = await User.findOne({ where: { email: email } });
+
+                const receiver = await User.findOne({ where: { email } });
                 if (!receiver) {
-                    return res.status(404).json({ message: '요청을 받을 사용자를 찾을 수 없습니다.' });
+                    throw new Error('요청을 받을 사용자를 찾을 수 없습니다.');
                 }
-                const friendId = receiver.id;
-                // 친구 요청 보내기 서비스 호출
-                const friendRequest = await FriendService.sendFriendRequest(userId, friendId);
+
+                const friendRequest = await FriendService.sendFriendRequest(userId, receiver.id);
                 return res.status(201).json({
-                    success:true,
-                    data:friendRequest
+                    success: true,
+                    data: friendRequest
                 });
-            } catch (error) {
-                // 유니크 제약조건 오류 처리
-                if (error.message === 'Friend request already exists') {
-                    return res.status(409).json({ message: error.message });
+            });
+        } catch (error) {
+            return res.status(error.status || 500).json({
+                success: false,
+                error: {
+                    message: error.message,
+                    code: 'FRIEND_REQUEST_ERROR'
                 }
-
-                // 일반 오류 처리
-                return res.status(500).json({ message: '서버 오류가 발생했습니다.', error: error.message });
-            }
+            });
         }
+    }
+
     /**
      * 받은 친구 요청 목록 조회
      * GET /api/friend/requests/received
      */
     async getReceivedRequests(req, res) {
         try {
-            const userId = req.user.id;
-            const requests = await FriendService.getReceivedRequests(userId);
-
-            return res.status(200).json({
-                success: true,
-                data: requests
+            return await performanceMonitor.measureAsync('getReceivedRequests', async () => {
+                const userId = req.user.id;
+                const requests = await FriendService.getReceivedRequests(userId);
+                return res.status(200).json({
+                    success: true,
+                    data: requests
+                });
             });
         } catch (error) {
             return res.status(500).json({
@@ -66,12 +72,13 @@ class friendController {
      */
     async getSentRequests(req, res) {
         try {
-            const userId = req.user.id;
-            const requests = await FriendService.getSentRequests(userId);
-
-            return res.status(200).json({
-                success: true,
-                data: requests
+            return await performanceMonitor.measureAsync('getSentRequests', async () => {
+                const userId = req.user.id;
+                const requests = await FriendService.getSentRequests(userId);
+                return res.status(200).json({
+                    success: true,
+                    data: requests
+                });
             });
         } catch (error) {
             return res.status(500).json({
@@ -83,21 +90,21 @@ class friendController {
             });
         }
     }
-    
     /**
      * 친구 요청 수락
      * POST /api/friend/request/:friendId/accept
      */
     async acceptRequest(req, res) {
         try {
-            const userId = req.user.id;
-            const { friendId } = req.params;
-
-            const result = await FriendService.acceptFriendRequest(userId, friendId);
-
-            return res.status(200).json({
-                success: true,
-                data: result
+            return await performanceMonitor.measureAsync('acceptFriendRequest', async () => {
+                const userId = req.user.id;
+                const { friendId } = req.params;
+
+                const result = await FriendService.acceptFriendRequest(userId, friendId);
+                return res.status(200).json({
+                    success: true,
+                    data: result
+                });
             });
         } catch (error) {
             return res.status(400).json({
@@ -116,14 +123,15 @@ class friendController {
      */
     async rejectRequest(req, res) {
         try {
-            const userId = req.user.id;
-            const { friendId } = req.params;
-
-            const result = await FriendService.rejectFriendRequest(userId, friendId);
-
-            return res.status(200).json({
-                success: true,
-                data: result
+            return await performanceMonitor.measureAsync('rejectFriendRequest', async () => {
+                const userId = req.user.id;
+                const { friendId } = req.params;
+
+                const result = await FriendService.rejectFriendRequest(userId, friendId);
+                return res.status(200).json({
+                    success: true,
+                    data: result
+                });
             });
         } catch (error) {
             return res.status(400).json({
@@ -142,23 +150,20 @@ class friendController {
      */
     async getFriendList(req, res) {
         try {
-            const userId = req.user.id;
-            const page = parseInt(req.query.page) || 0;
-            const size = parseInt(req.query.size) || 20;
-            
-            const friends = await FriendService.getFriendList(userId, {
-                limit: size,
-                offset: page * size
-            });
+            return await performanceMonitor.measureAsync('getFriendList', async () => {
+                const userId = req.user.id;
+                const page = parseInt(req.query.page) || 0;
+                const size = parseInt(req.query.size) || 20;
+
+                const friends = await FriendService.getFriendList(userId, {
+                    limit: size,
+                    offset: page * size
+                });
 
-            return res.status(200).json({
-                success: true,
-                data: {
-                    content: friends,
-                    page: page,
-                    size: size,
-                    hasNext: friends.length === size 
-                }
+                return res.status(200).json({
+                    success: true,
+                    data: friends
+                });
             });
         } catch (error) {
             return res.status(500).json({
@@ -177,17 +182,18 @@ class friendController {
      */
     async deleteFriend(req, res) {
         try {
-            const userId = req.user.id;
-            const { friendId } = req.params;
-
-            const result = await FriendService.deleteFriend(userId, friendId);
-
-            return res.status(200).json({
-                success: true,
-                data: {
-                    message: 'Friend deleted successfully',
-                    result: result
-                }
+            return await performanceMonitor.measureAsync('deleteFriend', async () => {
+                const userId = req.user.id;
+                const { friendId } = req.params;
+
+                const result = await FriendService.deleteFriend(userId, friendId);
+                return res.status(200).json({
+                    success: true,
+                    data: {
+                        message: 'Friend deleted successfully',
+                        result: result
+                    }
+                });
             });
         } catch (error) {
             return res.status(400).json({
diff --git a/services/friendService.js b/services/friendService.js
index 4d61554..5e16524 100644
--- a/services/friendService.js
+++ b/services/friendService.js
@@ -210,7 +210,7 @@ class FriendService {
                 }
             ],
             order: [['id', 'ASC']],
-            limit: limit + 1, // 다음 페이지 존재 여부 확인을 위해 1개 더 조회
+            limit: limit + 1, 
             offset
         });
     
-- 
GitLab