From d88cdcefd11e4463d4b35367f36cb9e74a94e821 Mon Sep 17 00:00:00 2001 From: Seongwoo_Lukaid Date: Wed, 6 Dec 2023 10:41:38 +0900 Subject: [PATCH] Refactor/api provider (#149) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * rename AuthContext to ApiProvider * feat: ApiProvider 도입 철회, axios의 client만 도입 * feat: 흩어져 있던 axios 모음 * error handling * feat: axios client로 모두 수정 --- client/src/App.tsx | 2 +- client/src/apis/Auth.ts | 16 ------- client/src/apis/apiClient.ts | 6 +++ client/src/apis/createRoom.ts | 22 +++++----- client/src/apis/exitRoom.ts | 10 +++-- client/src/apis/getSession.ts | 11 +++++ client/src/apis/joinRoom.ts | 16 +++---- client/src/apis/logout.ts | 9 ++++ client/src/apis/mockLogin.ts | 14 ++++++ client/src/apis/searchProblem.ts | 25 +++++------ client/src/components/Chat.tsx | 4 +- client/src/components/Profile.tsx | 4 +- .../src/components/buttons/LogoutButton.tsx | 2 +- .../components/buttons/RoomCreateButton.tsx | 11 +++-- client/src/components/temp/MockLogin.tsx | 19 ++++---- .../{AuthContext.tsx => AuthProvider.tsx} | 44 +++++++++---------- client/src/contexts/ThemeProvider.tsx | 7 ++- client/src/pages/Home.tsx | 2 +- client/src/pages/Lobby.tsx | 4 +- client/src/pages/ProtectedRoute.tsx | 2 +- 20 files changed, 122 insertions(+), 108 deletions(-) delete mode 100644 client/src/apis/Auth.ts create mode 100644 client/src/apis/apiClient.ts create mode 100644 client/src/apis/getSession.ts create mode 100644 client/src/apis/logout.ts create mode 100644 client/src/apis/mockLogin.ts rename client/src/contexts/{AuthContext.tsx => AuthProvider.tsx} (60%) diff --git a/client/src/App.tsx b/client/src/App.tsx index f3131d7..db69e9f 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,7 +1,7 @@ import { Outlet } from 'react-router-dom'; import { QueryClientProvider, QueryClient } from '@tanstack/react-query'; -import { AuthProvider } from './contexts/AuthContext'; +import { AuthProvider } from './contexts/AuthProvider'; import { ThemeProvider } from './contexts/ThemeProvider'; import ThemeComponent from './components/temp/ThemedComponent'; diff --git a/client/src/apis/Auth.ts b/client/src/apis/Auth.ts deleted file mode 100644 index b6051c6..0000000 --- a/client/src/apis/Auth.ts +++ /dev/null @@ -1,16 +0,0 @@ -import axios from 'axios'; -import { CreateUser } from '../types/CreateUserType'; - -const VITE_BASE_URL = import.meta.env.VITE_BASE_URL as string; - -export async function getSession(): Promise { - const response = await axios.get(`${VITE_BASE_URL}/session`, { - withCredentials: true, - }); - - return response.data; -} - -export async function logout() { - axios.get(`${VITE_BASE_URL}/auth/logout`, { withCredentials: true }); -} diff --git a/client/src/apis/apiClient.ts b/client/src/apis/apiClient.ts new file mode 100644 index 0000000..1015179 --- /dev/null +++ b/client/src/apis/apiClient.ts @@ -0,0 +1,6 @@ +import axios, { AxiosInstance } from 'axios'; + +export const apiClient: AxiosInstance = axios.create({ + baseURL: import.meta.env.VITE_BASE_URL as string, + withCredentials: true, +}); diff --git a/client/src/apis/createRoom.ts b/client/src/apis/createRoom.ts index 51a1d2c..188de77 100644 --- a/client/src/apis/createRoom.ts +++ b/client/src/apis/createRoom.ts @@ -1,14 +1,16 @@ -import axios from 'axios'; +import { AxiosError } from 'axios'; import { RoomCreateType } from '../types/RoomCreateType'; - -const VITE_BASE_URL = import.meta.env.VITE_BASE_URL as string; +import { apiClient } from './apiClient'; export async function createRoom(): Promise { - const response = await axios.post( - `${VITE_BASE_URL}/room`, - {}, - { withCredentials: true }, - ); - - return response.data; + try { + const { data } = await apiClient.post('/room', {}); + return data; + } catch (error) { + if (error instanceof AxiosError) { + // TODO: 이거 session로직 수정되면 여기도 고쳐야 됨 + // 세션에서 현재 유저가 방에 참가중인지, 어떤 방에 참가중인지 정보를 받아 올 수 있어야 함 + alert(error.response!.data.message); + } + } } diff --git a/client/src/apis/exitRoom.ts b/client/src/apis/exitRoom.ts index 810fd24..c922d9e 100644 --- a/client/src/apis/exitRoom.ts +++ b/client/src/apis/exitRoom.ts @@ -1,7 +1,9 @@ -import axios from 'axios'; - -const VITE_BASE_URL = import.meta.env.VITE_BASE_URL as string; +import { apiClient } from './apiClient'; export async function exitRoom() { - await axios.post(`${VITE_BASE_URL}/room/exit`, {}, { withCredentials: true }); + try { + await apiClient.post('/room/exit'); + } catch (error) { + console.log(error); + } } diff --git a/client/src/apis/getSession.ts b/client/src/apis/getSession.ts new file mode 100644 index 0000000..c3383b4 --- /dev/null +++ b/client/src/apis/getSession.ts @@ -0,0 +1,11 @@ +import { CreateUser } from '../types/CreateUserType'; +import { apiClient } from './apiClient'; + +export async function getSession(): Promise { + try { + const { data }: { data: CreateUser } = await apiClient.get('/session'); + return data; + } catch (error) { + console.log(error); + } +} diff --git a/client/src/apis/joinRoom.ts b/client/src/apis/joinRoom.ts index 42de52e..bcb731f 100644 --- a/client/src/apis/joinRoom.ts +++ b/client/src/apis/joinRoom.ts @@ -1,13 +1,9 @@ -import axios from 'axios'; - -const VITE_BASE_URL = import.meta.env.VITE_BASE_URL as string; +import { apiClient } from './apiClient'; export async function joinRoom(roomCode: string) { - await axios.post( - `${VITE_BASE_URL}/room/join`, - { code: roomCode }, - { - withCredentials: true, - }, - ); + try { + await apiClient.post('/room/join', { code: roomCode }); + } catch (error) { + console.log(error); + } } diff --git a/client/src/apis/logout.ts b/client/src/apis/logout.ts new file mode 100644 index 0000000..843284d --- /dev/null +++ b/client/src/apis/logout.ts @@ -0,0 +1,9 @@ +import { apiClient } from './apiClient'; + +export async function logout() { + try { + await apiClient.get('/auth/logout'); + } catch (error) { + console.log(error); + } +} diff --git a/client/src/apis/mockLogin.ts b/client/src/apis/mockLogin.ts new file mode 100644 index 0000000..39a3934 --- /dev/null +++ b/client/src/apis/mockLogin.ts @@ -0,0 +1,14 @@ +import { apiClient } from './apiClient'; + +type mockUser = { + username: string; + password: string; +}; + +export async function mockLoginApi(mockUser: mockUser) { + try { + return await apiClient.post('/auth/mock', mockUser); + } catch (error) { + console.log(error); + } +} diff --git a/client/src/apis/searchProblem.ts b/client/src/apis/searchProblem.ts index 2d57533..a2e010e 100644 --- a/client/src/apis/searchProblem.ts +++ b/client/src/apis/searchProblem.ts @@ -1,22 +1,21 @@ -import axios from 'axios'; import { ProblemResponse } from '../types/Problem'; -export async function searchProblem(searchKeyword: string): Promise { - const VITE_BASE_URL = import.meta.env.VITE_BASE_URL as string; +import { apiClient } from './apiClient'; - if(!searchKeyword) return Promise.resolve([]); +export async function searchProblem( + searchKeyword: string, +): Promise { + if (!searchKeyword) return Promise.resolve([]); - return await axios - .get(`${VITE_BASE_URL}/problem`, { + try { + const { data } = await apiClient.get('/problem', { params: { searchKeyword, }, - }) - .then((res) => { - return res.data || []; - }) - .catch((err) => { - console.log(err); - return []; }); + return data; + } catch (error) { + console.log(error); + return []; + } } diff --git a/client/src/components/Chat.tsx b/client/src/components/Chat.tsx index 71e2f23..83f8073 100644 --- a/client/src/components/Chat.tsx +++ b/client/src/components/Chat.tsx @@ -1,7 +1,7 @@ import { FaArrowRight } from 'react-icons/fa6'; import Message from './Message'; +import { useAuthContext } from '../contexts/AuthProvider'; import { ChatEvent, MessageInterface } from '../types/Message'; -import { useAuthContext } from '../contexts/AuthContext'; import { Socket } from 'socket.io-client'; // TODO: userColor -> 서버에서 설정 @@ -36,7 +36,7 @@ export default function Chat({ username: user?.username || 'Anonymous', body: inputText, chatEvent: ChatEvent.Message, - color: 'text-purple', // TODO: 서버에서 설정 + color: 'text-purple', // TODO: 클라에서 랜덤 설정 }; socket.emit('chat-message', newChatMessage); diff --git a/client/src/components/Profile.tsx b/client/src/components/Profile.tsx index 88b5da5..bcb4ddc 100644 --- a/client/src/components/Profile.tsx +++ b/client/src/components/Profile.tsx @@ -1,4 +1,4 @@ -import { useAuthContext } from '../contexts/AuthContext'; +import { useAuthContext } from '../contexts/AuthProvider'; export default function Profile() { const { user } = useAuthContext(); @@ -11,7 +11,7 @@ export default function Profile() { src={user!.avatarUrl} alt="프로필 이미지" /> -

+

{user!.username}

diff --git a/client/src/components/buttons/LogoutButton.tsx b/client/src/components/buttons/LogoutButton.tsx index 519a881..d3a857c 100644 --- a/client/src/components/buttons/LogoutButton.tsx +++ b/client/src/components/buttons/LogoutButton.tsx @@ -1,4 +1,4 @@ -import { useAuthUpdateContext } from '../../contexts/AuthContext'; +import { useAuthUpdateContext } from '../../contexts/AuthProvider'; export default function LogoutButton() { const { onLogout } = useAuthUpdateContext(); diff --git a/client/src/components/buttons/RoomCreateButton.tsx b/client/src/components/buttons/RoomCreateButton.tsx index 1aedd0c..4881594 100644 --- a/client/src/components/buttons/RoomCreateButton.tsx +++ b/client/src/components/buttons/RoomCreateButton.tsx @@ -12,12 +12,11 @@ export default function RoomCreateButton() { try { const roomInfo: RoomCreateType | undefined = await createRoom(); if (roomInfo === undefined) { - setTimeout(() => { - console.log(roomInfo); - alert('방 생성에 실패했습니다.'); - setIsLoading(false); - }, 1000); - + // setTimeout(() => { + // alert('방 생성에 실패했습니다.'); + // + // }, 1000); + setIsLoading(false); return; } const roomCode = roomInfo.code; diff --git a/client/src/components/temp/MockLogin.tsx b/client/src/components/temp/MockLogin.tsx index 3624fe4..30c819f 100644 --- a/client/src/components/temp/MockLogin.tsx +++ b/client/src/components/temp/MockLogin.tsx @@ -1,17 +1,14 @@ -import axios from 'axios'; +import { mockLoginApi } from '../../apis/mockLogin'; export default function MockLogin() { - const baseURL = import.meta.env.VITE_BASE_URL; - async function mockLogin({ id }: { id: string }) { const mockUser = { username: `mock${id}`, password: `mock${id}`, }; - const response = await axios.post(`${baseURL}/auth/mock`, mockUser, { - withCredentials: true, - }); - if (response.status === 201) { + const response = await mockLoginApi(mockUser); + console.log(response); + if (response?.status === 201) { console.log(response.data); // AuthProvider의 useEffect가 실행되지 않아서 새로고침을 해줘야 함 // 원래라면 AuthProvider에 따로 메서드를 만들어줘야하는게 맞는데 mock이라서 그냥 새로고침으로 대체 @@ -23,7 +20,7 @@ export default function MockLogin() {