Skip to content

Commit

Permalink
카테고리, 게시글 목록 연동 및 리팩터링 (#219)
Browse files Browse the repository at this point in the history
* feat: (#205) 카테고리에 관련된 API 서버와 연동
wus폴더에 있던 파일들 밖으로 이동

* feat: (#205) 게시글 작성 페이지에서 카테고리 리스트를 불러와 옵션으로 변환하는 기능 구현

* refactor: (#205) 마감 시간을 구하는 유틸 함수 분리

* refactor: (#205) sua 폴더에 있던 post.ts MSW 코드를 밖의 post.ts 파일과 병합

* refactor: (#205) wus 폴더에 있던 유저 MSW 코드 밖으로 이동

* refactor: (#205) wus 폴더의 게시글 목록 MSW 코드를 밖으로 분리 및 파일명 변경

* refactor: (#205) api 폴더에 있던 wus 폴더 삭제 및 파일 이동

* refactor: (#205) 댓글을 제외한 나머지 api에 BASE_URL 코드 추가

* refactor: (#205) AuthContext에서 User 타입 변경 및 액세스 토큰이 있을 경우 isLogged:true로 수정

* fix: (#205) 게시글의 카테고리 리스트에 ?를 붙혀 없어도 에러가 나지 않게 수정

* feat: (#205) 게시글 서버에서 받는 타입 명세 선언

* refactor: (#205) 서버에서 받은 게시글 목록을 클라이언트에서 사용하는 게시글 목록 명세로 변환

* refactor: (#205) 게시글 명세인 startTime, endTime의 이름을 변경
  • Loading branch information
Gilpop8663 authored Aug 3, 2023
1 parent 7ef315f commit 626f753
Show file tree
Hide file tree
Showing 40 changed files with 395 additions and 228 deletions.
2 changes: 1 addition & 1 deletion frontend/__test__/api/categoryList.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
getUserCategoryList,
removeFavoriteCategory,
transformCategoryListResponse,
} from '@api/wus/categoryList';
} from '@api/categoryList';

import { MOCK_CATEGORY_LIST, MOCK_GUEST_CATEGORY_LIST } from '@mocks/mockData/categoryList';

Expand Down
12 changes: 6 additions & 6 deletions frontend/__test__/api/postList.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { getPostList } from '@api/postList';

import { POST_TYPE, SORTING, STATUS } from '@constants/post';

import { MOCK_POST_LIST } from '@mocks/mockData/postList';
import { MOCK_TRANSFORM_POST_LIST } from '@mocks/mockData/postList';

describe('서버와 통신하여 전체 게시글 목록을 불러오는지 확인한다.', () => {
test('게시글 목록의 개수는 10개씩 불러온다.', async () => {
Expand Down Expand Up @@ -36,7 +36,7 @@ describe('서버와 통신하여 전체 게시글 목록을 불러오는지 확
}
);

expect(data.postList).toEqual(MOCK_POST_LIST);
expect(data.postList).toEqual(MOCK_TRANSFORM_POST_LIST);
});

test('게시글 페이지의 정보를 불러온다.', async () => {
Expand Down Expand Up @@ -70,7 +70,7 @@ describe('서버와 통신하여 전체 게시글 목록을 불러오는지 확
}
);

expect(data.postList).toEqual(MOCK_POST_LIST);
expect(data.postList).toEqual(MOCK_TRANSFORM_POST_LIST);
});

test('내가 작성한 게시글 페이지의 정보를 불러온다.', async () => {
Expand All @@ -87,7 +87,7 @@ describe('서버와 통신하여 전체 게시글 목록을 불러오는지 확
}
);

expect(data.postList).toEqual(MOCK_POST_LIST);
expect(data.postList).toEqual(MOCK_TRANSFORM_POST_LIST);
});

test('내가 투표한 게시글 페이지의 정보를 불러온다.', async () => {
Expand All @@ -104,7 +104,7 @@ describe('서버와 통신하여 전체 게시글 목록을 불러오는지 확
}
);

expect(data.postList).toEqual(MOCK_POST_LIST);
expect(data.postList).toEqual(MOCK_TRANSFORM_POST_LIST);
});

test('내가 검색한 게시글 페이지의 정보를 불러온다.', async () => {
Expand All @@ -121,6 +121,6 @@ describe('서버와 통신하여 전체 게시글 목록을 불러오는지 확
}
);

expect(data.postList).toEqual(MOCK_POST_LIST);
expect(data.postList).toEqual(MOCK_TRANSFORM_POST_LIST);
});
});
2 changes: 1 addition & 1 deletion frontend/__test__/api/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
getUserInfo,
modifyNickname,
transformUserInfoResponse,
} from '@api/wus/userInfo';
} from '@api/userInfo';

import { MOCK_USER_INFO } from '@mocks/mockData/user';

Expand Down
27 changes: 27 additions & 0 deletions frontend/__test__/changeCategoryToOption.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Category } from '@type/category';

import { Option } from '@components/common/MultiSelect/types';

import { changeCategoryToOption } from '@utils/post/changeCategoryToOption';

describe('changeCategoryToOption 함수를 이용해서 카테고리 리스트를 셀렉트 컴포넌트에 사용되는 옵션 리스트로 변환한다.', () => {
test('카테고리 리스트로 옵션 리스트를 만든다.', () => {
const categoryList: Category[] = [
{ id: 1, isFavorite: false, name: '갤럭시' },
{ id: 2, isFavorite: true, name: '애플' },
];

const result: Option[] = changeCategoryToOption(categoryList);

expect(result).toEqual([
{
id: 1,
name: '갤럭시',
},
{
id: 2,
name: '애플',
},
]);
});
});
53 changes: 53 additions & 0 deletions frontend/__test__/getDeadlineTime.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { getDeadlineTime } from '@utils/post/getDeadlineTime';

describe('getDeadlineTime를 이용하여 사용자에게 마감 시간을 알려준다.', () => {
test('5분을 설정했을 때 5분으로 표시된다', () => {
const result = getDeadlineTime({
day: 0,
hour: 0,
minute: 5,
});

expect(result).toBe('5분 후에 마감됩니다.');
});

test('1시간 5분을 설정했을 때 1시간 5분으로 표시된다', () => {
const result = getDeadlineTime({
day: 0,
hour: 1,
minute: 5,
});

expect(result).toBe('1시간 5분 후에 마감됩니다.');
});

test('2일 23시간 59분을 설정했을 때 2일 23시간 59분으로 표시된다', () => {
const result = getDeadlineTime({
day: 2,
hour: 23,
minute: 59,
});

expect(result).toBe('2일 23시간 59분 후에 마감됩니다.');
});

test('0일 0시간 0분을 설정했을 때 "마감 시간을 선택해주세요"를 표시된다', () => {
const result = getDeadlineTime({
day: 0,
hour: 0,
minute: 0,
});

expect(result).toBe('마감 시간을 선택해주세요');
});

test('-1일 -1시간 -1분을 설정했을 때 "마감 시간을 다시 설정해주세요"를 표시된다', () => {
const result = getDeadlineTime({
day: -1,
hour: -1,
minute: -1,
});

expect(result).toBe('마감 시간을 다시 설정해주세요');
});
});
48 changes: 48 additions & 0 deletions frontend/__test__/hooks/query/useCategoryList.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React, { ReactNode } from 'react';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook, waitFor } from '@testing-library/react';

import { useCategoryList } from '@hooks/query/category/useCategoryList';

import { transformCategoryListResponse } from '@api/categoryList';

import { MOCK_CATEGORY_LIST, MOCK_GUEST_CATEGORY_LIST } from '@mocks/mockData/categoryList';

const queryClient = new QueryClient();

const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);

describe('useCategoryList 훅이 카테고리 목록을 불러오는지 확인한다.', () => {
test('비회원 카테고리 목록을 불러온다.', async () => {
const { result } = renderHook(() => useCategoryList(false), {
wrapper,
});

await waitFor(() =>
expect(result.current.data).toEqual(transformCategoryListResponse(MOCK_GUEST_CATEGORY_LIST))
);
});

test('회원 카테고리 목록을 불러온다.', async () => {
const { result } = renderHook(() => useCategoryList(true), {
wrapper,
});

await waitFor(() =>
expect(result.current.data).toEqual(transformCategoryListResponse(MOCK_CATEGORY_LIST))
);
});

test('회원 카테고리 목록을 불러온다.', async () => {
const { result } = renderHook(() => useCategoryList(true), {
wrapper,
});

await waitFor(() =>
expect(result.current.data).toEqual(transformCategoryListResponse(MOCK_CATEGORY_LIST))
);
});
});
22 changes: 16 additions & 6 deletions frontend/__test__/hooks/query/usePostList.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { usePostList } from '@hooks/query/usePostList';

import { POST_TYPE, SORTING, STATUS } from '@constants/post';

import { MOCK_POST_LIST } from '@mocks/mockData/postList';
import { MOCK_TRANSFORM_POST_LIST } from '@mocks/mockData/postList';

const queryClient = new QueryClient();

Expand Down Expand Up @@ -35,7 +35,9 @@ describe('usePostList 훅이 게시글 목록을 불러오는지 확인한다.',
}
);

await waitFor(() => expect(result.current.data?.pages[0].postList).toEqual(MOCK_POST_LIST));
await waitFor(() =>
expect(result.current.data?.pages[0].postList).toEqual(MOCK_TRANSFORM_POST_LIST)
);
});

test('카테고리별 게시글 목록을 불러온다.', async () => {
Expand All @@ -57,7 +59,9 @@ describe('usePostList 훅이 게시글 목록을 불러오는지 확인한다.',
}
);

await waitFor(() => expect(result.current.data?.pages[0].postList).toEqual(MOCK_POST_LIST));
await waitFor(() =>
expect(result.current.data?.pages[0].postList).toEqual(MOCK_TRANSFORM_POST_LIST)
);
});

test('내가 작성한 게시글 목록을 불러온다.', async () => {
Expand All @@ -79,7 +83,9 @@ describe('usePostList 훅이 게시글 목록을 불러오는지 확인한다.',
}
);

await waitFor(() => expect(result.current.data?.pages[0].postList).toEqual(MOCK_POST_LIST));
await waitFor(() =>
expect(result.current.data?.pages[0].postList).toEqual(MOCK_TRANSFORM_POST_LIST)
);
});

test('내가 투표한 게시글 목록을 불러온다.', async () => {
Expand All @@ -101,7 +107,9 @@ describe('usePostList 훅이 게시글 목록을 불러오는지 확인한다.',
}
);

await waitFor(() => expect(result.current.data?.pages[0].postList).toEqual(MOCK_POST_LIST));
await waitFor(() =>
expect(result.current.data?.pages[0].postList).toEqual(MOCK_TRANSFORM_POST_LIST)
);
});

test('내가 검색한 게시글 목록을 불러온다.', async () => {
Expand All @@ -123,6 +131,8 @@ describe('usePostList 훅이 게시글 목록을 불러오는지 확인한다.',
}
);

await waitFor(() => expect(result.current.data?.pages[0].postList).toEqual(MOCK_POST_LIST));
await waitFor(() =>
expect(result.current.data?.pages[0].postList).toEqual(MOCK_TRANSFORM_POST_LIST)
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,24 @@ export const transformCategoryListResponse = (categoryList: CategoryResponse[])
}));
};

const BASE_URL = process.env.VOTOGETHER_BASE_URL;

export const getUserCategoryList = async () => {
const categoryList = await getFetch<CategoryResponse[]>('/categories');
const categoryList = await getFetch<CategoryResponse[]>(`${BASE_URL}/categories`);

return transformCategoryListResponse(categoryList);
};

export const getGuestCategoryList = async () => {
const categoryList = await getFetch<CategoryResponse[]>('/categories/guest');
const categoryList = await getFetch<CategoryResponse[]>(`${BASE_URL}/categories/guest`);

return transformCategoryListResponse(categoryList);
};

export const addFavoriteCategory = async (categoryId: number) => {
await postFetch(`/categories/${categoryId}/like`, '');
await postFetch(`${BASE_URL}/categories/${categoryId}/like`, '');
};

export const removeFavoriteCategory = async (categoryId: number) => {
await deleteFetch(`/categories/${categoryId}/like`);
await deleteFetch(`${BASE_URL}/categories/${categoryId}/like`);
};
1 change: 1 addition & 0 deletions frontend/src/api/comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export const transformCommentListResponse = (commentList: CommentResponse[]): Co
isEdit: comment.createdAt !== comment.updatedAt,
}));
};

export const getCommentList = async (postId: number): Promise<Comment[]> => {
const commentList = await getFetch<CommentResponse[]>(`/posts/${postId}/comments`);

Expand Down
43 changes: 36 additions & 7 deletions frontend/src/api/post.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PostInfo } from '@type/post';
import { PostInfo, PostInfoResponse } from '@type/post';

import {
getFetch,
Expand All @@ -11,8 +11,35 @@ import {

const BASE_URL = process.env.VOTOGETHER_BASE_URL;

export const transformPostResponse = (post: PostInfoResponse): PostInfo => {
return {
category: post.categories.map(category => ({ id: category.id, name: category.name })),
content: post.content,
deadline: post.deadline,
imageUrl: post.imageUrl,
postId: post.postId,
createTime: post.createdAt,
title: post.title,
voteInfo: {
allPeopleCount: post.voteInfo.totalVoteCount,
selectedOptionId: post.voteInfo.selectedOptionId,
options: post.voteInfo.options.map(option => ({
id: option.optionId,
text: option.content,
peopleCount: option.voteCount,
percent: option.votePercent,
imageUrl: option.imageUrl,
})),
},
writer: {
id: post.writer.id,
nickname: post.writer.nickname,
},
};
};

export const votePost = async (postId: number, optionId: number) => {
return await postFetch(`/posts/${postId}/options/${optionId}`, '');
return await postFetch(`${BASE_URL}/posts/${postId}/options/${optionId}`, '');
};

interface OptionData {
Expand All @@ -22,26 +49,28 @@ interface OptionData {

export const changeVotedOption = async (postId: number, optionData: OptionData) => {
return await patchFetch(
`/posts/${postId}/options?source=${optionData.originOptionId}&target=${optionData.newOptionId}`
`${BASE_URL}/posts/${postId}/options?source=${optionData.originOptionId}&target=${optionData.newOptionId}`
);
};

export const getPost = async (postId: number): Promise<PostInfo> => {
return await getFetch<PostInfo>(`/posts/${postId}`);
const post = await getFetch<PostInfoResponse>(`${BASE_URL}/posts/${postId}`);

return transformPostResponse(post);
};

export const createPost = async (newPost: FormData) => {
return await multiPostFetch(`${BASE_URL}/posts`, newPost);
};

export const editPost = async (postId: number, updatedPost: FormData) => {
return await multiPutFetch(`http://3.35.232.54/api/posts/${postId}`, updatedPost);
return await multiPutFetch(`${BASE_URL}/posts/${postId}`, updatedPost);
};

export const removePost = async (postId: number) => {
return await deleteFetch(`/posts/${postId}`);
return await deleteFetch(`${BASE_URL}/posts/${postId}`);
};

export const setEarlyClosePost = async (postId: number) => {
return await patchFetch(`/posts/${postId}/close`);
return await patchFetch(`${BASE_URL}/posts/${postId}/close`);
};
Loading

0 comments on commit 626f753

Please sign in to comment.