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

feat: token refetch 로직 추가 #32

Merged
merged 2 commits into from
Mar 20, 2023
Merged
Show file tree
Hide file tree
Changes from all 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: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
"@next/font": "13.1.6",
"@tanstack/react-query": "4.24.6",
"@toss/emotion-utils": "^1.1.5",
"@toss/react": "^1.3.7",
"@toss/use-overlay": "^1.3.1",
"@toss/utils": "^1.4.1",
"axios": "1.3.3",
"framer-motion": "^10.0.0",
"next": "13.1.6",
Expand Down
39 changes: 35 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 24 additions & 2 deletions src/apis/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,25 @@ export const authToken = {
return null;
}
})(),
refetch: () => {
authToken.access = localStorage.getItem('accessToken');
authToken.refresh = localStorage.getItem('refreshToken');
return;
},
destroy: () => {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
authToken.access = null;
authToken.refresh = null;
},
};

export const axiosClient = axios.create({
baseURL: process.env.NODE_ENV === 'development' ? DEV_SERVER_URL : PROD_SERVER_URL,
headers: {
Authorization: `Bearer ${authToken.access}`,
'Content-Type': 'application/json; charset=utf-8',
timeout: 5000,
},
});

Expand Down Expand Up @@ -117,8 +129,17 @@ axiosClient.interceptors.request.use(
if (config?.headers == null) {
throw new Error(`config.header is undefined`);
}
config.headers['Content-Type'] = 'application/json; charset=utf-8';

if (config.headers['Authorization'] == `Bearer ${null}`) {
authToken.refetch();
}

if (axiosClient.defaults.headers.common['Authorization'] == `Bearer ${null}`) {
authToken.refetch();
}

config.headers['Authorization'] = `Bearer ${authToken.access}`;
axiosClient.defaults.headers.common['Authorization'] = `Bearer ${authToken.access}`;

return config;
},
Expand Down Expand Up @@ -150,7 +171,8 @@ axiosClient.interceptors.response.use(
return originalResponse.data.data;
}
} catch (err) {
if (isEffError(error) && error.errorCode === 401) {
if (isEffError(err) && err.errorCode === 401) {
console.log(err);
redirectToLoginPage();
await delay(500);
return null;
Expand Down
8 changes: 8 additions & 0 deletions src/apis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ export async function postResetPassword(email: string, password: string, confirm
return await axiosClient.post('/members/password-reset', { email, password, confirmPassword });
}

//user 정보 fetching
export async function getUser() {
const {
data: { nickname, email },
} = await axiosClient.get<User>('/members/profile');
return { nickname, email };
}

export const getMainCategories = async () => {
const {
data: { categories },
Expand Down
13 changes: 13 additions & 0 deletions src/components/common/SSRSuspense/index.tsx
chaaerim marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Suspense } from 'react';
import { useIsMounted } from '@toss/react';
import type { ComponentProps } from 'react';

export function SSRSuspense(props: ComponentProps<typeof Suspense>) {
const isMounted = useIsMounted();

if (!isMounted) {
return <>{props.fallback}</>;
}

return <Suspense {...props} />;
}
4 changes: 1 addition & 3 deletions src/hooks/form/useCheckLoginForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useMutation } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';

import { postLogin } from '~/apis';
import { authToken, isEffError } from '~/apis/client';
import { isEffError } from '~/apis/client';
import { emailPattern, passwordPattern } from '~/constants/validationPattern';

import { useToast } from '../useToast';
Expand Down Expand Up @@ -53,8 +53,6 @@ export const useCheckLoginForm = () => {
const { accessToken, refreshToken } = data;
localStorage.setItem('accessToken', accessToken);
localStorage.setItem('refreshToken', refreshToken);
}
if (authToken.access && authToken.refresh) {
router.push('/category');
}
} catch (error: unknown) {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useShowLoginModal } from '~/hooks/useShowLoginModal';

export default function Home() {
// TODO: redirect page 재설정하기
const showLoginModal = useShowLoginModal('login');
const showLoginModal = useShowLoginModal('category');
return (
<Flex.Center direction="column">
<HomeHeader />
Expand Down
5 changes: 5 additions & 0 deletions src/types/response.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,8 @@ interface QuestionAnswerResponse {
id: number;
answer: string;
}

interface User {
nickname: string;
email: string;
}