-   Notifications  You must be signed in to change notification settings 
- Fork 0
[25.04.22 / TASK-100] Feature - Leaderboard 도메인 추가 및 조회 API 구현 #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
   Merged  
     Merged  
 Changes from 8 commits
 Commits 
  Show all changes 
  14 commits   Select commit Hold shift + click to select a range 
 72cdb9d  feature: Leaderboard 도메인 파일 세팅 및 타입 추가 
  ooheunda 8f8feb3  feature: Leaderboard 조회 API 구현 
  ooheunda 3b26d44  modify: Leaderboard 조회시 type 분기는 post를 먼저 하도록 통일 
  ooheunda 9a194dd  test: Leaderboard 조회 API 서비스, 리포지토리 계층 단위 테스트 추가 
  ooheunda 4d79f7d  modify: Leaderboard Repo 쿼리시 오는 RawResult 타입 정의 
  ooheunda 4765e25  test: Leaderboard 조회 API 서비스 계층 단위 테스트 케이스 추가 
  ooheunda d99696e  modify: 코드래빗 리뷰 반영 
  ooheunda e15be82  modify: 관련 타입 index.ts에 넣고 import 부분 수정 
  ooheunda abc3a3a  modify: 사용자, 게시물 별로 Leaderboard 조회 API 분리 
  ooheunda ce5f111  modify: 분리중 자동완성에서 생긴 불필요한 쿼리 삭제 
  ooheunda 651add9  modify: 리뷰 기반 테스트 코드 수정 
  ooheunda f8627cb  modify: API 분리하며 불필요해진 swagger 주석 삭제 
  ooheunda afa5fcf  modify: bigint PK를 string으로 받도록 타입 수정 
  ooheunda 3fa3cb1  modify: sortCol 변환을 삼항연산자에서 객체 형식으로 수정 
  ooheunda File filter
Filter by extension
Conversations
 Failed to load comments.  
    Loading  
 Jump to
  Jump to file  
  Failed to load files.  
    Loading  
 Diff view
Diff view
There are no files selected for viewing
   This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters   
     | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import logger from '@/configs/logger.config'; | ||
| import { NextFunction, RequestHandler, Request, Response } from 'express'; | ||
| import { LeaderboardService } from '@/services/leaderboard.service'; | ||
| import { GetLeaderboardQuery, LeaderboardResponseDto } from '@/types/index'; | ||
|  | ||
| export class LeaderboardController { | ||
| constructor(private leaderboardService: LeaderboardService) {} | ||
|  | ||
| getLeaderboard: RequestHandler = async ( | ||
| req: Request<object, object, object, GetLeaderboardQuery>, | ||
| res: Response<LeaderboardResponseDto>, | ||
| next: NextFunction, | ||
| ) => { | ||
| try { | ||
| const { type, sort, dateRange, limit } = req.query; | ||
|  | ||
| const result = await this.leaderboardService.getLeaderboard(type, sort, dateRange, limit); | ||
| const response = new LeaderboardResponseDto(true, '리더보드 조회에 성공하였습니다.', result, null); | ||
|  | ||
| res.status(200).json(response); | ||
| } catch (error) { | ||
| logger.error('리더보드 조회 실패:', error); | ||
| next(error); | ||
| } | ||
| }; | ||
| } | 
   This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters   
     | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,244 @@ | ||
| import { Pool, QueryResult } from 'pg'; | ||
| import { DBError } from '@/exception'; | ||
| import { LeaderboardRepository } from '@/repositories/leaderboard.repository'; | ||
|  | ||
| jest.mock('pg'); | ||
|  | ||
| const mockPool: { | ||
| query: jest.Mock<Promise<QueryResult<Record<string, unknown>>>, unknown[]>; | ||
| } = { | ||
| query: jest.fn(), | ||
| }; | ||
|  | ||
| describe('LeaderboardRepository', () => { | ||
| let repo: LeaderboardRepository; | ||
|  | ||
| beforeEach(() => { | ||
| repo = new LeaderboardRepository(mockPool as unknown as Pool); | ||
| }); | ||
|  | ||
| describe('getLeaderboard', () => { | ||
| it('type이 post인 경우 post 데이터를 반환해야 한다.', async () => { | ||
| const mockResult = [ | ||
| { | ||
| id: 2, | ||
| title: 'test2', | ||
| slug: 'test2', | ||
| total_views: 200, | ||
| total_likes: 100, | ||
| view_diff: 20, | ||
| like_diff: 10, | ||
| released_at: '2025-01-02', | ||
| }, | ||
| { | ||
| id: 1, | ||
| title: 'test', | ||
| slug: 'test', | ||
| total_views: 100, | ||
| total_likes: 50, | ||
| view_diff: 10, | ||
| like_diff: 5, | ||
| released_at: '2025-01-01', | ||
| }, | ||
| ]; | ||
|  | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: mockResult, | ||
| rowCount: mockResult.length, | ||
| } as unknown as QueryResult); | ||
|   ooheunda marked this conversation as resolved. Outdated   Show resolved Hide resolved | ||
|  | ||
| const result = await repo.getLeaderboard('post', 'viewCount', 30, 10); | ||
|  | ||
| expect(result).toEqual(mockResult); | ||
| expect(mockPool.query).toHaveBeenCalledWith(expect.stringContaining('FROM posts_post p'), expect.anything()); | ||
| }); | ||
|  | ||
| it('type이 user인 경우 user 데이터를 반환해야 한다.', async () => { | ||
| const mockResult = [ | ||
| { | ||
| id: 1, | ||
| email: 'test@test.com', | ||
| total_views: 100, | ||
| total_likes: 50, | ||
| total_posts: 1, | ||
| view_diff: 20, | ||
| like_diff: 10, | ||
| post_diff: 1, | ||
| }, | ||
| { | ||
| id: 2, | ||
| email: 'test2@test.com', | ||
| total_views: 200, | ||
| total_likes: 100, | ||
| total_posts: 2, | ||
| view_diff: 10, | ||
| like_diff: 5, | ||
| post_diff: 1, | ||
| }, | ||
| ]; | ||
|  | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: mockResult, | ||
| rowCount: mockResult.length, | ||
| } as unknown as QueryResult); | ||
|  | ||
| const result = await repo.getLeaderboard('user', 'viewCount', 30, 10); | ||
|  | ||
| expect(mockPool.query).toHaveBeenCalledWith(expect.stringContaining('FROM users_user u'), expect.anything()); | ||
| expect(result).toEqual(mockResult); | ||
| }); | ||
|  | ||
| it('sort가 조회수인 경우 정렬 순서를 보장해야 한다.', async () => { | ||
| const mockResult = [ | ||
| { view_diff: 20, like_diff: 5, post_diff: 1 }, | ||
| { view_diff: 10, like_diff: 10, post_diff: 2 }, | ||
| ]; | ||
|  | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: mockResult, | ||
| rowCount: mockResult.length, | ||
| } as unknown as QueryResult); | ||
|  | ||
| const result = await repo.getLeaderboard('user', 'viewCount', 30, 10); | ||
|  | ||
| expect(result).toEqual(mockResult); | ||
| expect(result[0].view_diff).toBeGreaterThan(result[1].view_diff); | ||
| }); | ||
|  | ||
| it('sort가 좋아요 수인 경우 정렬 순서를 보장해야 한다.', async () => { | ||
| const mockResult = [ | ||
| { view_diff: 10, like_diff: 10, post_diff: 1 }, | ||
| { view_diff: 20, like_diff: 5, post_diff: 1 }, | ||
| ]; | ||
|  | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: mockResult, | ||
| rowCount: mockResult.length, | ||
| } as unknown as QueryResult); | ||
|  | ||
| const result = await repo.getLeaderboard('user', 'likeCount', 30, 10); | ||
|  | ||
| expect(result).toEqual(mockResult); | ||
| expect(result[0].like_diff).toBeGreaterThan(result[1].like_diff); | ||
| }); | ||
|  | ||
| it('sort가 게시물 수인 경우 정렬 순서를 보장해야 한다.', async () => { | ||
| const mockResult = [ | ||
| { view_diff: 10, like_diff: 10, post_diff: 4 }, | ||
| { view_diff: 20, like_diff: 5, post_diff: 1 }, | ||
| ]; | ||
|  | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: mockResult, | ||
| rowCount: mockResult.length, | ||
| } as unknown as QueryResult); | ||
|  | ||
| const result = await repo.getLeaderboard('user', 'postCount', 30, 10); | ||
|  | ||
| expect(result).toEqual(mockResult); | ||
| expect(result[0].post_diff).toBeGreaterThan(result[1].post_diff); | ||
| }); | ||
|  | ||
| it('limit 만큼의 데이터만 반환해야 한다', async () => { | ||
| const mockData = [ | ||
| { id: 1, title: 'test' }, | ||
| { id: 2, title: 'test2' }, | ||
| { id: 3, title: 'test3' }, | ||
| { id: 4, title: 'test4' }, | ||
| { id: 5, title: 'test5' }, | ||
| ]; | ||
| const mockLimit = 5; | ||
|  | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: mockData, | ||
| rowCount: mockData.length, | ||
| } as unknown as QueryResult); | ||
|  | ||
| const result = await repo.getLeaderboard('post', 'viewCount', 30, mockLimit); | ||
|  | ||
| expect(result).toEqual(mockData); | ||
| expect(result.length).toEqual(mockLimit); | ||
|  | ||
| expect(mockPool.query).toHaveBeenCalledWith( | ||
| expect.stringContaining('LIMIT $2'), | ||
| expect.arrayContaining([30, mockLimit]), | ||
| ); | ||
| }); | ||
|  | ||
| it('type이 post이고 sort가 게시물 수인 경우 조회수를 기준으로 정렬해야 한다.', async () => { | ||
| const mockResult = [ | ||
| { total_views: 200, total_likes: 5, view_diff: 20, like_diff: 0 }, | ||
| { total_views: 100, total_likes: 50, view_diff: 10, like_diff: 5 }, | ||
| ]; | ||
|  | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: mockResult, | ||
| rowCount: mockResult.length, | ||
| } as unknown as QueryResult); | ||
|  | ||
| const result = await repo.getLeaderboard('post', 'postCount', 30, 10); | ||
|  | ||
| expect(result).toEqual(mockResult); | ||
| expect(mockPool.query).toHaveBeenCalledWith( | ||
| expect.stringContaining('ORDER BY view_diff DESC'), | ||
| expect.anything(), | ||
| ); | ||
| expect(result[0].view_diff).toBeGreaterThan(result[1].view_diff); | ||
| }); | ||
|  | ||
| it('user 타입에는 GROUP BY 절이 포함되어야 한다', async () => { | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: [], | ||
| rowCount: 0, | ||
| } as unknown as QueryResult); | ||
|  | ||
| await repo.getLeaderboard('user', 'viewCount', 30, 10); | ||
|  | ||
| expect(mockPool.query).toHaveBeenCalledWith(expect.stringContaining('GROUP BY u.id, u.email'), expect.anything()); | ||
| }); | ||
|  | ||
| it('post 타입에는 GROUP BY 절이 포함되지 않아야 한다', async () => { | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: [], | ||
| rowCount: 0, | ||
| } as unknown as QueryResult); | ||
|  | ||
| await repo.getLeaderboard('post', 'viewCount', 30, 10); | ||
|  | ||
| expect(mockPool.query).toHaveBeenCalledWith(expect.not.stringContaining('GROUP BY'), expect.anything()); | ||
| }); | ||
|  | ||
| it('dateRange 파라미터가 쿼리에 올바르게 적용되어야 한다', async () => { | ||
| const mockResult = [{ id: 1 }]; | ||
| const testDateRange = 30; | ||
|  | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: mockResult, | ||
| rowCount: mockResult.length, | ||
| } as unknown as QueryResult); | ||
|  | ||
| await repo.getLeaderboard('user', 'viewCount', testDateRange, 10); | ||
|  | ||
| expect(mockPool.query).toHaveBeenCalledWith( | ||
| expect.stringContaining('$1::int'), | ||
| expect.arrayContaining([testDateRange, expect.anything()]), | ||
| ); | ||
| }); | ||
|  | ||
| it('데이터가 없는 경우 빈 배열을 반환해야 한다', async () => { | ||
| mockPool.query.mockResolvedValue({ | ||
| rows: [], | ||
| rowCount: 0, | ||
| } as unknown as QueryResult); | ||
|  | ||
| const result = await repo.getLeaderboard('user', 'viewCount', 30, 10); | ||
|  | ||
| expect(result).toEqual([]); | ||
| }); | ||
|  | ||
| it('에러 발생 시 DBError를 던져야 한다', async () => { | ||
| mockPool.query.mockRejectedValue(new Error('DB connection failed')); | ||
| await expect(repo.getLeaderboard('post', 'postCount', 30, 10)).rejects.toThrow(DBError); | ||
| }); | ||
| }); | ||
| }); | ||
  Oops, something went wrong.  
  Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.    
 
Uh oh!
There was an error while loading. Please reload this page.