diff --git a/src/_api/axiosInstance.ts b/src/_api/axiosInstance.ts index 908e7df..263825c 100644 --- a/src/_api/axiosInstance.ts +++ b/src/_api/axiosInstance.ts @@ -1,4 +1,6 @@ import axios from 'axios'; +import NO_TOKEN_ENDPOINTS from './constant/noTokenEndPoints'; +import isAuthRequired from './util/isAuthRequired'; import { getAccessToken, _LOGIN_NEED_MESSAGE_ } from './storage/authStorage'; const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL; @@ -12,16 +14,22 @@ const axiosInstance = axios.create({ }, }); -const NO_TOKEN_ENDPOINTS = ['/auth/signUp', '/auth/signIn', '/oauthApps']; - axiosInstance.interceptors.request.use( (config) => { - const token = getAccessToken(); //dino@gmail.com, 12341234 //임시 토큰 // const token = // 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NzMyLCJ0ZWFtSWQiOiIxMC0zIiwiaWF0IjoxNzM0NTEzNTUyLCJpc3MiOiJzcC1tb2dhem9hIn0.tbvOoiH-iTR1CZW5rhjJW5KSr2Go8cxGwqRWxLGwqZ8'; + const path = config.url || ''; + const method = config?.method || ''; + + if (!isAuthRequired(path, method)) { + return config; + } + + const token = getAccessToken(); + if (!token && config.url && !NO_TOKEN_ENDPOINTS.includes(config.url)) { throw new Error(`Failed to getAccessToken(), ${_LOGIN_NEED_MESSAGE_}`); } diff --git a/src/_api/constant/noTokenEndPoints.ts b/src/_api/constant/noTokenEndPoints.ts new file mode 100644 index 0000000..3e7d6bd --- /dev/null +++ b/src/_api/constant/noTokenEndPoints.ts @@ -0,0 +1,9 @@ +const NO_TOKEN_ENDPOINTS = [ + '/auth/', + '/categories', + '/oauthApps', + '/products', + `/users/`, +]; + +export default NO_TOKEN_ENDPOINTS; diff --git a/src/_api/util/isAuthRequired.ts b/src/_api/util/isAuthRequired.ts new file mode 100644 index 0000000..496f8fb --- /dev/null +++ b/src/_api/util/isAuthRequired.ts @@ -0,0 +1,19 @@ +import NO_TOKEN_ENDPOINTS from '../constant/noTokenEndPoints'; + +const isAuthRequired = (path: string, method: string): boolean => { + if (path === '/users/me') { + return true; + } + + if (path.startsWith('/users/')) { + return false; + } + + if (method === 'POST' && path.startsWith('/products')) { + return true; + } + + return !NO_TOKEN_ENDPOINTS.some((endpoint) => path.startsWith(endpoint)); +}; + +export default isAuthRequired;