From 4e8a65926f9f6f1a6244aeaefa7949ed96ac92bf Mon Sep 17 00:00:00 2001 From: hwookim Date: Mon, 13 Feb 2023 22:11:12 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20refreshToken=20=EB=B0=9C=EA=B8=89=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/apis/auth.ts | 21 +++++++++++++++++++++ src/configs/axios.ts | 24 +++++++++++++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/apis/auth.ts b/src/apis/auth.ts index 7a6716d..4948748 100644 --- a/src/apis/auth.ts +++ b/src/apis/auth.ts @@ -1,5 +1,6 @@ import axios from 'axios'; +import { localstorageKeys } from '@src/constants/localstorage'; import { Onboarding } from '@src/pages/onboarding/index.page'; import { BaseResponse } from '.'; @@ -54,3 +55,23 @@ export const checkNickName = async (nickName: string) => { return res.data.data; }; + +export type RefreshTokenResponse = BaseResponse; +export const refreshToken = async () => { + const user = localStorage.getItem(localstorageKeys.user); + if (!user) return; + const { refreshToken } = JSON.parse(user) as Auth['jwtTokens']; + if (!refreshToken) return; + + const res = await axios.post(`/refresh`, null, { + headers: { + 'refresh-token': refreshToken, + }, + }); + const code = res.data.code; + if (Number(code) === 2003 || Number(code) === 2005 || Number(code) === 2006) { + localStorage.removeItem(localstorageKeys.user); + } + + return res.data.data; +}; diff --git a/src/configs/axios.ts b/src/configs/axios.ts index fcdab1d..4bc96be 100644 --- a/src/configs/axios.ts +++ b/src/configs/axios.ts @@ -1,6 +1,6 @@ import axios, { AxiosRequestConfig } from 'axios'; -import { Auth } from '@src/apis'; +import { Auth, refreshToken } from '@src/apis'; import { localstorageKeys } from '@src/constants/localstorage'; export const BASE_URL = process.env.NEXT_PUBLIC_API_URL; @@ -22,4 +22,26 @@ export const interceptorsAxiosConfig = () => { } return config; }); + + axios.interceptors.response.use( + (res) => res, + async (err) => { + const { config, response } = err; + const code = response.data.code; + + if (Number(code) !== 2002) { + return Promise.reject(err); + } + + config.sent = true; + const jwtTokens = await refreshToken(); + if (!jwtTokens) { + localStorage.removeItem(localstorageKeys.user); + return Promise.reject(err); + } + localStorage.setItem(localstorageKeys.user, JSON.stringify(jwtTokens)); + + return axios(config); + }, + ); };