Skip to content

Commit

Permalink
Merge pull request codestates-seb#310 from shimdokite/develop
Browse files Browse the repository at this point in the history
[FE] ✨ axios 컴포넌트 구현 및 react query hooks 네이밍 리팩토링
  • Loading branch information
nalsae authored Oct 19, 2023
2 parents 48374a3 + e4f6791 commit 42d64e6
Show file tree
Hide file tree
Showing 28 changed files with 102 additions and 189 deletions.
34 changes: 13 additions & 21 deletions client/src/api/axios.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
import axios, {
AxiosRequestConfig,
AxiosResponse,
InternalAxiosRequestConfig,
} from 'axios';

import useUserStore from '@/stores/userStore';

const { setAccessToken } = useUserStore();
import axios, { AxiosResponse } from 'axios';

const accessToken =
typeof window !== 'undefined'
Expand All @@ -18,7 +10,7 @@ const refreshToken =
? JSON.parse(localStorage.getItem('user-key') as string).state.refreshToken
: null;

const instance = axios.create({
export const instance = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: {
Authorization: accessToken,
Expand All @@ -27,7 +19,8 @@ const instance = axios.create({
withCredentials: true,
});

// atob을 활용한 JWT 디코딩
const storageData = JSON.parse(localStorage.getItem('user-key') as string);

const parseJWT = (token: string | null) => {
if (token) return JSON.parse(atob(token.split('.')[1]));
};
Expand All @@ -36,27 +29,28 @@ const authVerify = () => {
const decodedAccess = parseJWT(accessToken);
const decodedRefresh = parseJWT(refreshToken);

if (decodedAccess.exp * 1000 < Date.now()) {
if (decodedAccess?.exp * 1000 < Date.now()) {
return 'Access Token Expired';
}

if (decodedRefresh.exp * 1000 < Date.now()) {
if (decodedRefresh?.exp * 1000 < Date.now()) {
return 'Refresh Token Expired';
}

return true;
};

// 응답 받기 전, 새로운 accessToke이 존재하면 바꿔주기
export const onFulfiled = async (response: AxiosResponse) => {
const onFulfiled = async (response: AxiosResponse) => {
if (authVerify() === 'Access Token Expired') {
const { authorization: newAccessToken } = response.headers;
const { authorization: newAccessToken } = response?.headers;

storageData.state.accessToken = newAccessToken;

setAccessToken(newAccessToken);
localStorage.setItem('user-key', JSON.stringify(storageData));

// 타입 호환을 위해 새로운 객체를 만들어서 업데이트하기
response.config.headers = Object.assign({}, response.config.headers, {
authorization: `${newAccessToken}`,
refresh: refreshToken ?? '',
});

return await axios(response.config);
Expand All @@ -66,9 +60,7 @@ export const onFulfiled = async (response: AxiosResponse) => {
};

instance.interceptors.request.use(
//! AxiosRequestConfig 대신 InternalAxiosRequestConfig를 사용하라고 하는데...
// InternalAxiosRequestConfig를 개발자가 직접 건드는게 좋은건 아니라고 하던데 흠...
async (config: InternalAxiosRequestConfig) => {
async (config) => {
config.headers = config.headers ?? {};

if (accessToken) {
Expand Down
33 changes: 7 additions & 26 deletions client/src/api/history.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,13 @@
import axios from 'axios';

const accessToken =
typeof window !== 'undefined'
? JSON.parse(localStorage.getItem('user-key') as string).state.accessToken
: null;

const refreshToken =
typeof window !== 'undefined'
? JSON.parse(localStorage.getItem('user-key') as string).state.refreshToken
: null;

export const historyAxios = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: {
Authorization: accessToken,
Refresh: refreshToken,
},
withCredentials: true,
});
import { instance } from './axios';

export const getUserInfo = async (id: string) => {
const { data } = await historyAxios.get(`/accounts/${id}`);
const { data } = await instance.get(`/accounts/${id}`);

return data;
};

export const postUserPassword = async (password: string) => {
const { data, headers } = await historyAxios.post(
const { data, headers } = await instance.post(
`/accounts/password/verification`,
{
password,
Expand All @@ -37,21 +18,21 @@ export const postUserPassword = async (password: string) => {
};

export const deleteUser = async () => {
const { status } = await historyAxios.delete(`/accounts`);
const { status } = await instance.delete(`/accounts`);

return status;
};

export const getBoardWrittenByPage = async ({ pageParam = 1 }, id: string) => {
const response = await historyAxios
const response = await instance
.get(`/accounts/boardWritten/${id}?page=${pageParam}`)
.then((response) => response.data);

return { boardWritten: response.data, pageInfo: response.pageInfo };
};

export const getBoardLikedByPage = async ({ pageParam = 1 }, id: string) => {
const response = await historyAxios
const response = await instance
.get(`/accounts/boardLiked/${id}?page=${pageParam}`)
.then((response) => response.data);

Expand All @@ -62,7 +43,7 @@ export const getCommentWrittenByPage = async (
{ pageParam = 1 },
id: string,
) => {
const response = await historyAxios
const response = await instance
.get(`/accounts/commentWritten/${id}?page=${pageParam}`)
.then((response) => response.data);

Expand Down
46 changes: 10 additions & 36 deletions client/src/api/profile.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,7 @@
import axios from 'axios';

const accessToken =
typeof window !== 'undefined'
? JSON.parse(localStorage.getItem('user-key') as string).state.accessToken
: null;

const refreshToken =
typeof window !== 'undefined'
? JSON.parse(localStorage.getItem('user-key') as string).state.refreshToken
: null;

export const historyAxios = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: {
Authorization: accessToken,
Refresh: refreshToken,
},
withCredentials: true,
});
import { instance } from './axios';

export const updateUserNickname = async (displayName: string) => {
const { data, headers, status } = await historyAxios.patch(
const { data, headers, status } = await instance.patch(
`/accounts/displayname`,
{
displayName,
Expand All @@ -34,13 +15,10 @@ export const updateUserPassword = async (
presentPassword: string,
changedPassword: string,
) => {
const { data, headers, status } = await historyAxios.patch(
`/accounts/password`,
{
presentPassword,
changedPassword,
},
);
const { data, headers, status } = await instance.patch(`/accounts/password`, {
presentPassword,
changedPassword,
});

return { data, headers, status };
};
Expand All @@ -53,15 +31,11 @@ export const updateUserProfileImage = async (file: File) => {
const formData = new FormData();
formData.append('profileImage', file);

const response = await historyAxios.patch(
`/accounts/profileimage`,
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
},
const response = await instance.patch(`/accounts/profileimage`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
);
});

return response.data;
};
4 changes: 2 additions & 2 deletions client/src/components/history/ConfirmModal.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
'use client';

import useDeleteUser from '@/hooks/mutation/useDeleteUser';
import useDeleteUserMutation from '@/hooks/mutation/useDeleteUserMutation';

import { CommonButton, Modal, ModalPortal } from '../common';

export default function ConfirmModal() {
const { onDeleteUser, close } = useDeleteUser();
const { mutate: onDeleteUser, close } = useDeleteUserMutation();

return (
<ModalPortal>
Expand Down
12 changes: 3 additions & 9 deletions client/src/components/history/HistoryBoard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,24 @@
import { useRouter } from 'next/navigation';
import InfiniteScroll from 'react-infinite-scroller';

import useUserStore from '@/stores/userStore';

import useHistoryBoard from '@/hooks/useHistoryBoard';
import useHistoryBoardQuery from '@/hooks/query/useHistoryBoardQuery';

import { HistoryPostCard } from '.';
import EmptyDiary from '../leaf/EmptyDiary';
import { EmptyDiary } from '../leaf';
import { ErrorMessage, LoadingMessage } from '../common';

import { HistoryBoradProps } from '@/types/common';

export default function HistoryBoard({ paramsId }: HistoryBoradProps) {
const router = useRouter();

const { userId } = useUserStore();

const {
data: boards,
fetchNextPage,
hasNextPage,
isLoading,
isError,
} = useHistoryBoard(paramsId);
} = useHistoryBoardQuery(paramsId);

const likesAmount = (likes: []) => {
if (likes?.length === 0) return 0;
Expand All @@ -41,8 +37,6 @@ export default function HistoryBoard({ paramsId }: HistoryBoradProps) {
key={index}
className="w-[715px] my-4 max-[730px]:w-[512px] max-[630px]:w-[312px] flex justify-center items-center ml-1">
<EmptyDiary
pathUserId={paramsId}
userId={userId}
info="board"
addInfo="addBoard"
className="max-w-[314px] max-[507px]:mx-3 max-[430px]:w-[214px] text-[13px]"
Expand Down
12 changes: 3 additions & 9 deletions client/src/components/history/HistoryComment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,24 @@
import { useRouter } from 'next/navigation';
import InfiniteScroll from 'react-infinite-scroller';

import useUserStore from '@/stores/userStore';

import useHistoryComment from '@/hooks/useHistoryComment';
import useHistoryCommentQuery from '@/hooks/query/useHistoryCommentQuery';

import { HistoryPostCard } from '.';
import EmptyDiary from '../leaf/EmptyDiary';
import { EmptyDiary } from '../leaf';
import { ErrorMessage, LoadingMessage } from '../common';

import { HistoryBoradProps } from '@/types/common';

export default function HistoryComment({ paramsId }: HistoryBoradProps) {
const router = useRouter();

const { userId } = useUserStore();

const {
data: comments,
fetchNextPage,
hasNextPage,
isLoading,
isError,
} = useHistoryComment(paramsId);
} = useHistoryCommentQuery(paramsId);

const likesAmount = (likes: []) => {
if (likes?.length === 0) return 0;
Expand All @@ -41,8 +37,6 @@ export default function HistoryComment({ paramsId }: HistoryBoradProps) {
key={index}
className="w-[715px] my-4 max-[730px]:w-[512px] max-[630px]:w-[312px] flex justify-center items-center ml-1">
<EmptyDiary
pathUserId={paramsId}
userId={userId}
info="comment"
className="max-w-[314px] max-[507px]:mx-3 max-[430px]:w-[214px] text-[13px]"
/>
Expand Down
12 changes: 3 additions & 9 deletions client/src/components/history/HistoryLikes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,24 @@
import { useRouter } from 'next/navigation';
import InfiniteScroll from 'react-infinite-scroller';

import useHistoryLikes from '@/hooks/useHistoryLikes';

import useUserStore from '@/stores/userStore';
import useHistoryLikesQuery from '@/hooks/query/useHistoryLikesQuery';

import { HistoryPostCard } from '.';
import EmptyDiary from '../leaf/EmptyDiary';
import { EmptyDiary } from '../leaf';
import { ErrorMessage, LoadingMessage } from '../common';

import { HistoryBoradProps } from '@/types/common';

export default function HistoryLikes({ paramsId }: HistoryBoradProps) {
const router = useRouter();

const { userId } = useUserStore();

const {
data: likes,
fetchNextPage,
hasNextPage,
isLoading,
isError,
} = useHistoryLikes(paramsId);
} = useHistoryLikesQuery(paramsId);

const likesAmount = (likes: []) => {
if (likes?.length === 0) return 0;
Expand All @@ -41,8 +37,6 @@ export default function HistoryLikes({ paramsId }: HistoryBoradProps) {
key={index}
className="w-[715px] my-4 max-[730px]:w-[512px] max-[630px]:w-[312px] flex justify-center items-center ml-1">
<EmptyDiary
pathUserId={paramsId}
userId={userId}
info="likes"
className="max-w-[314px] max-[507px]:mx-3 max-[430px]:w-[214px] text-[13px]"
/>
Expand Down
4 changes: 2 additions & 2 deletions client/src/components/history/ResignModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { useForm } from 'react-hook-form';

import useResignCheck from '@/hooks/useResignCheck';
import useResignCheckMutation from '@/hooks/mutation/useResignCheckMutation';

import { SignModalInput } from '../sign';
import { CommonButton, Modal, ModalPortal } from '../common';
Expand All @@ -17,7 +17,7 @@ export default function ResignModal() {
formState: { errors, isSubmitting },
} = useForm<SignFormValue>();

const { onPasswordCheck, close } = useResignCheck();
const { mutate: onPasswordCheck, close } = useResignCheckMutation();

const userPassword = watch('password');

Expand Down
4 changes: 2 additions & 2 deletions client/src/components/history/UserInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useRouter } from 'next/navigation';
import useUserStore from '@/stores/userStore';

import useClient from '@/hooks/useClient';
import useUserInfo from '@/hooks/useUserInfo';
import useUserInfoQuery from '@/hooks/query/useUserInfoQuery';

import { CommonButton } from '../common';

Expand All @@ -22,7 +22,7 @@ export default function UserInfo({ paramsId }: HistoryUserProps) {
const { userId } = useUserStore();

const isClient = useClient();
const { profileImageUrl, displayName, grade, point } = useUserInfo(id);
const { profileImageUrl, displayName, grade, point } = useUserInfoQuery(id);

return (
<div className="flex flex-col justify-center items-center">
Expand Down
Loading

0 comments on commit 42d64e6

Please sign in to comment.