From 8eda3e9c25b1c6eb0253b278c792a7d8d0ed614f 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: Mon, 25 Nov 2024 20:50:08 +0900 Subject: [PATCH] =?UTF-8?q?refactor:=20friend=20pagination=20=EB=B0=A9?= =?UTF-8?q?=EC=8B=9D=20=EC=88=98=EC=A0=95=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/friendController.js | 18 +++++++++++++++--- routes/friend.js | 2 +- services/friendService.js | 21 +++++++++++++++------ 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/controllers/friendController.js b/controllers/friendController.js index 8f385c7..c3eb251 100644 --- a/controllers/friendController.js +++ b/controllers/friendController.js @@ -137,15 +137,27 @@ class friendController { /** * 친구 목록 조회 - * GET /api/friend/all/:offset + * GET /api/friend/all?page=1&size=20 */ async getFriendList(req, res) { try { const userId = req.user.id; - const friends = await FriendService.getFriendList(userId,20,req.param); + 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: friends + data: { + content: friends, + page: page, + size: size, + hasNext: friends.length === size + } }); } catch (error) { return res.status(500).json({ diff --git a/routes/friend.js b/routes/friend.js index 53145a9..6061959 100644 --- a/routes/friend.js +++ b/routes/friend.js @@ -37,7 +37,7 @@ router.post('/request/:friendId/reject', FriendController.rejectRequest); /** * 친구 목록 조회 - * GET /api/friend/all + * GET /api/friend/all?page=1&size=20 */ router.get('/all', FriendController.getFriendList); diff --git a/services/friendService.js b/services/friendService.js index bb995bb..d35b3c7 100644 --- a/services/friendService.js +++ b/services/friendService.js @@ -191,7 +191,9 @@ class FriendService { * @param {number} offset - 페이징 오프셋 * @returns {Promise<Array<FriendListDTO>>} - 친구 목록 DTO 배열 */ - async getFriendList(userId, limit = 20, offset = 0) { + async getFriendList(userId, pagination) { + const { limit = 20, offset = 0 } = pagination; + const friends = await Friend.findAll({ where: { [Op.or]: [ @@ -212,13 +214,20 @@ class FriendService { attributes: ['id', 'name', 'email'] } ], - order: [['id', 'ASC']], - limit, + order: [['id', 'ASC']], + limit: limit + 1, // 다음 페이지 존재 여부 확인을 위해 1개 더 조회 offset }); - - - return friends.map(friend => new FriendListDTO(friend, userId)); + + const hasNext = friends.length > limit; + const content = friends.slice(0, limit).map(friend => new FriendListDTO(friend, userId)); + + return { + content, + page: offset / limit, + size: limit, + hasNext + }; } /** -- GitLab