Skip to content
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

Refactor/api provider #149

Merged
merged 6 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion client/src/App.tsx
Original file line number Diff line number Diff line change
@@ -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';

Expand Down
13 changes: 0 additions & 13 deletions client/src/apis/Auth.ts

This file was deleted.

6 changes: 6 additions & 0 deletions client/src/apis/apiClient.ts
Original file line number Diff line number Diff line change
@@ -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,
});
8 changes: 3 additions & 5 deletions client/src/apis/createRoom.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import axios from 'axios';
import { RoomCreateType } from '../types/RoomCreateType';
import { apiClient } from './apiClient';

export async function createRoom(): Promise<RoomCreateType | undefined> {
const VITE_BASE_URL = import.meta.env.VITE_BASE_URL as string;

return await axios
.post(`${VITE_BASE_URL}/room`, {
return await apiClient
.post('/room', {
userId: 1,
})
.then((response) => {
Expand Down
6 changes: 6 additions & 0 deletions client/src/apis/getSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { apiClient } from './apiClient';

export async function getSession() {
const { data } = await apiClient.get('/session');
return data;
}
5 changes: 5 additions & 0 deletions client/src/apis/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { apiClient } from './apiClient';

export async function logout() {
await apiClient.get('/auth/logout');
}
10 changes: 10 additions & 0 deletions client/src/apis/mockLogin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { apiClient } from './apiClient';

type mockUser = {
username: string;
password: string;
};

export async function mockLoginApi(mockUser: mockUser) {
return await apiClient.post('/auth/mock', mockUser);
}
2 changes: 1 addition & 1 deletion client/src/components/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from '../types/Message';
import { FaArrowRight } from 'react-icons/fa6';
import Message from './Message';
import { useAuthContext } from '../contexts/AuthContext';
import { useAuthContext } from '../contexts/AuthProvider';
import { useParams } from 'react-router-dom';

// TODO: userColor -> 서버에서 설정
Expand Down
4 changes: 2 additions & 2 deletions client/src/components/Profile.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useAuthContext } from '../contexts/AuthContext';
import { useAuthContext } from '../contexts/AuthProvider';

export default function Profile() {
const { user } = useAuthContext();
Expand All @@ -11,7 +11,7 @@ export default function Profile() {
src={user!.avatarUrl}
alt="프로필 이미지"
/>
<p className="text-text_default text-lg font-semibold">
<p className="text-lg font-semibold text-text_default">
{user!.username}
</p>
</div>
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/buttons/LogoutButton.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useAuthUpdateContext } from '../../contexts/AuthContext';
import { useAuthUpdateContext } from '../../contexts/AuthProvider';

export default function LogoutButton() {
const { onLogout } = useAuthUpdateContext();
Expand Down
17 changes: 7 additions & 10 deletions client/src/components/temp/MockLogin.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
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,
});
const response = await mockLoginApi(mockUser);
console.log(response);
if (response.status === 201) {
console.log(response.data);
// AuthProvider의 useEffect가 실행되지 않아서 새로고침을 해줘야 함
Expand All @@ -23,31 +20,31 @@ export default function MockLogin() {
<div className="flex gap-2">
<button
id="1"
className="text-text_default bg-default_black my-2 flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm hover:hover:bg-opacity-50"
className="my-2 flex items-center gap-2 rounded-lg bg-default_black px-4 py-2.5 text-sm text-text_default hover:hover:bg-opacity-50"
onClick={() => {
mockLogin({ id: '1' });
}}>
Mock 1
</button>
<button
id="2"
className="text-text_default bg-default_black my-2 flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm hover:hover:bg-opacity-50"
className="my-2 flex items-center gap-2 rounded-lg bg-default_black px-4 py-2.5 text-sm text-text_default hover:hover:bg-opacity-50"
onClick={() => {
mockLogin({ id: '2' });
}}>
Mock 2
</button>
<button
id="3"
className="text-text_default bg-default_black my-2 flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm hover:hover:bg-opacity-50"
className="my-2 flex items-center gap-2 rounded-lg bg-default_black px-4 py-2.5 text-sm text-text_default hover:hover:bg-opacity-50"
onClick={() => {
mockLogin({ id: '3' });
}}>
Mock 3
</button>
<button
id="4"
className="text-text_default bg-default_black my-2 flex items-center gap-2 rounded-lg px-4 py-2.5 text-sm hover:hover:bg-opacity-50"
className="my-2 flex items-center gap-2 rounded-lg bg-default_black px-4 py-2.5 text-sm text-text_default hover:hover:bg-opacity-50"
onClick={() => {
mockLogin({ id: '4' });
}}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { useNavigate } from 'react-router-dom';
import { createContext, useContext, useEffect, useState } from 'react';
import {
ReactNode,
createContext,
useContext,
useEffect,
useState,
} from 'react';
import { CreateUser } from '../types/CreateUserType';
import axios from 'axios';
import { logout } from '../apis/logout';
import { getSession } from '../apis/getSession';

interface AuthContextType {
user: CreateUser | null;
Expand All @@ -11,34 +18,29 @@ interface AuthUpdateType {
onLogout: () => void;
}

const baseURL = import.meta.env.VITE_BASE_URL;
interface AuthProviderProps {
children: ReactNode;
}

const AuthContext = createContext<AuthContextType>({} as AuthContextType);
const AuthUpdateContext = createContext<AuthUpdateType>({} as AuthUpdateType);

export const AuthProvider = ({ children }: { children: JSX.Element }) => {
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const navigate = useNavigate();

const [user, setUser] = useState<CreateUser | null>(null);

const onLogout = () => {
// TODO: waiting for server api
axios.get(`${baseURL}/auth/logout`, { withCredentials: true });
logout();
setUser(null);
navigate('/');
};

useEffect(() => {
async function getSession() {
const response = await axios.get(`${baseURL}/session`, {
withCredentials: true,
});
return response;
}

getSession().then((session) => {
if (session) {
setUser(session.data);
getSession().then((data) => {
if (data) {
setUser(data);
} else {
setUser(null);
}
Expand Down
7 changes: 3 additions & 4 deletions client/src/contexts/ThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ type Theme =
| 'atom-one-light'
| 'github-dark'
| 'github-light';

type ThemeContextType = {
theme: Theme;
toggleTheme: () => void;
};

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
const ThemeContext = createContext<ThemeContextType>({} as ThemeContextType);

interface ThemeProviderProps {
children: ReactNode;
Expand All @@ -27,17 +28,15 @@ interface ThemeProviderProps {
const localStorageKey = 'theme';

export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
// Retrieve theme from localStorage or use 'default' as the default value
const storedTheme = localStorage.getItem(localStorageKey) as Theme | null;
const [theme, setTheme] = useState<Theme>(storedTheme || 'atom-one-dark');

useEffect(() => {
// Update data-theme attribute when the theme changes
document.documentElement.setAttribute('data-theme', theme);
// Save the theme to localStorage
localStorage.setItem(localStorageKey, theme);
}, [theme]);

// TODO: change setting function
const toggleTheme = () => {
setTheme((prevTheme) => {
switch (prevTheme) {
Expand Down
2 changes: 1 addition & 1 deletion client/src/pages/Home.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useNavigate } from 'react-router-dom';
import { useAuthContext } from '../contexts/AuthContext';
import { useAuthContext } from '../contexts/AuthProvider';
import GithubLoginButton from '../components/buttons/GithubLoginButton';
import { useEffect } from 'react';
import MockLogin from '../components/temp/MockLogin';
Expand Down
4 changes: 1 addition & 3 deletions client/src/pages/Lobby.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@ import LogoutButton from '../components/buttons/LogoutButton';
import Profile from '../components/Profile';
import RoomAccessPanel from '../components/RoomAccessPanel';

// import axios from 'axios';

export default function Lobby() {
return (
<div className="bg-bg min-h-screen">
<div className="min-h-screen bg-bg">
<div className="flex w-full justify-end">
<LogoutButton />
</div>
Expand Down
2 changes: 1 addition & 1 deletion client/src/pages/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Navigate } from 'react-router-dom';
import { useAuthContext } from '../contexts/AuthContext';
import { useAuthContext } from '../contexts/AuthProvider';

export default function ProtectedRoute({
children,
Expand Down