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] fetch instance 기능 보강 #450

Merged
merged 5 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
36 changes: 27 additions & 9 deletions src/common/apis/instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,40 @@ const baseURL = import.meta.env.VITE_BASE_URL;
type StandardHeaders = 'Content-Type' | 'Authorization' | 'Accept' | 'Cache-Control' | 'User-Agent';
type RequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';

interface FetchOptions extends RequestInit {
export class CustomError extends Error {
status: number;

constructor(message: string, status: number) {
super(message);
this.status = status;
}
}

eonseok-jeon marked this conversation as resolved.
Show resolved Hide resolved
interface FetchOptions extends Omit<RequestInit, 'body'> {
method?: RequestMethod;
headers?: Record<StandardHeaders, string>;
headers?: Partial<Record<StandardHeaders, string>>;
body?: Record<string, unknown>;
params?: Record<string, any>;
}

const instance = async (url: string, options: FetchOptions = {}) => {
eonseok-jeon marked this conversation as resolved.
Show resolved Hide resolved
const response = await fetch(`${baseURL}${url}`, {
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
const { body, params, headers = {}, ...rest } = options;
const urlWithParams = params ? `${url}?${new URLSearchParams(params).toString()}` : url;
const isFormData = body instanceof FormData;

if (!isFormData) {
headers['Content-Type'] = 'application/json';
}

const response = await fetch(`${baseURL}${urlWithParams}`, {
headers,
body: isFormData ? body : JSON.stringify(body),
...rest,
});

if (!response.ok) {
throw new Error('network response가 도착하지 않았어요');
const errMsg = await response.json();
throw new CustomError(errMsg.userMessage, response.status);
}

return response.json();
Expand Down
12 changes: 6 additions & 6 deletions src/common/components/Input/apis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ export const checkUser = async (userInfo: CheckUserRequest) => {
const { email, name, season, group } = userInfo;
const res = await instance('/recruiting-auth/check/user', {
method: 'POST',
body: JSON.stringify({
body: {
email,
name,
season,
group,
}),
},
});

return res;
Expand All @@ -20,12 +20,12 @@ export const checkUser = async (userInfo: CheckUserRequest) => {
export const sendVerificationCode = async (email: string, season: number, group: string, isSignup: boolean) => {
const res = await instance('/recruiting-auth/verify/send', {
method: 'POST',
body: JSON.stringify({
body: {
email,
season,
group,
isSignup,
}),
},
});

return res;
Expand All @@ -34,10 +34,10 @@ export const sendVerificationCode = async (email: string, season: number, group:
export const checkVerificationCode = async (email: string, code: string) => {
const res = await instance('/recruiting-auth/verify/email', {
method: 'POST',
body: JSON.stringify({
body: {
email,
code,
}),
},
});

return res;
Expand Down
9 changes: 4 additions & 5 deletions src/common/components/Input/hooks/useMutateCheckCode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import { VALIDATION_CHECK } from '@constants/validationCheck';
import { checkVerificationCode } from '../apis';

import type { CheckVerificationCodeRequest, EmailResponse } from '../types';
import type { ErrorResponse } from '@type/errorResponse';
import type { AxiosError, AxiosResponse } from 'axios';
import type { CustomError } from '@apis/instance';

interface MutateCheckCodeProps {
onSuccess: () => void;
Expand All @@ -17,14 +16,14 @@ const useMutateCheckCode = ({ onSuccess }: MutateCheckCodeProps) => {
const { setError } = useFormContext();

const { mutate: checkVerificationCodeMutate, isPending: checkVerificationCodeIsPending } = useMutation<
AxiosResponse<EmailResponse, CheckVerificationCodeRequest>,
AxiosError<ErrorResponse, CheckVerificationCodeRequest>,
EmailResponse,
CustomError,
CheckVerificationCodeRequest
>({
mutationFn: ({ email, code }: CheckVerificationCodeRequest) => checkVerificationCode(email, code),
onSuccess,
onError(error) {
if (error.response?.status === 400) {
if (error.status === 400) {
setError('code', {
type: 'not-match',
message: VALIDATION_CHECK.verificationCode.errorText,
Expand Down
9 changes: 4 additions & 5 deletions src/common/components/Input/hooks/useMutateCheckUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import { VALIDATION_CHECK } from '@constants/validationCheck';
import { checkUser } from '../apis';

import type { CheckUserRequest, EmailResponse } from '../types';
import type { ErrorResponse } from '@type/errorResponse';
import type { AxiosError, AxiosResponse } from 'axios';
import type { CustomError } from '@apis/instance';

interface MutateCheckUserProps {
onSendCode: () => void;
Expand All @@ -17,8 +16,8 @@ const useMutateCheckUser = ({ onSendCode }: MutateCheckUserProps) => {
const { clearErrors, setError } = useFormContext();

const { mutate: checkUserMutate, isPending: checkUserIsPending } = useMutation<
AxiosResponse<EmailResponse, CheckUserRequest>,
AxiosError<ErrorResponse, CheckUserRequest>,
EmailResponse,
CustomError,
CheckUserRequest
>({
mutationFn: (userInfo: CheckUserRequest) => checkUser(userInfo),
Expand All @@ -27,7 +26,7 @@ const useMutateCheckUser = ({ onSendCode }: MutateCheckUserProps) => {
onSendCode();
},
onError: (error) => {
if (error.response?.status === 400 || error.response?.status === 403) {
if (error.status === 400 || error.status === 403) {
setError('name', {
type: 'non-existence',
message: VALIDATION_CHECK.name.errorTextNonexistence,
Expand Down
9 changes: 4 additions & 5 deletions src/common/components/Input/hooks/useMutateSendCode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import { VALIDATION_CHECK } from '@constants/validationCheck';
import { sendVerificationCode } from '../apis';

import type { EmailResponse, SendVerificationCodeRequest } from '../types';
import type { ErrorResponse } from '@type/errorResponse';
import type { AxiosError, AxiosResponse } from 'axios';
import type { CustomError } from '@apis/instance';

interface MutateSendCodeProps {
onChangeVerification: (bool: boolean) => void;
Expand All @@ -18,8 +17,8 @@ const useMutateSendCode = ({ onChangeVerification, onSetTimer }: MutateSendCodeP
const { setError } = useFormContext();

const { mutate: sendVerificationCodeMutate, isPending: sendVerificationCodeIsPending } = useMutation<
AxiosResponse<EmailResponse, SendVerificationCodeRequest>,
AxiosError<ErrorResponse, SendVerificationCodeRequest>,
EmailResponse,
CustomError,
SendVerificationCodeRequest
>({
mutationFn: ({ email, season, group, isSignup }: SendVerificationCodeRequest) =>
Expand All @@ -29,7 +28,7 @@ const useMutateSendCode = ({ onChangeVerification, onSetTimer }: MutateSendCodeP
onSetTimer();
},
onError: (error) => {
if (error.response?.status === 400 || error.response?.status === 403) {
if (error.status === 400 || error.status === 403) {
setError('email', {
type: 'already-existence',
message: VALIDATION_CHECK.email.errorTextExistence,
Expand Down
4 changes: 2 additions & 2 deletions src/common/hooks/useDate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const useDate = () => {
obInterviewStart,
ybInterviewEnd,
obInterviewEnd,
} = data?.data.season || {};
} = data?.season || {};

const applicationStart = group === 'YB' ? ybApplicationStart : obApplicationStart; // 서류 시작
const applicationEnd = group === 'YB' ? ybApplicationEnd : obApplicationEnd; // 서류 마감
Expand Down Expand Up @@ -98,7 +98,7 @@ const useDate = () => {
]);

return {
...data?.data.season,
...data?.season,
NoMoreRecruit,
NoMoreApply,
NoMoreScreeningResult,
Expand Down
10 changes: 2 additions & 8 deletions src/common/hooks/useGetRecruitingInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,11 @@ import { useQuery } from '@tanstack/react-query';

import { getRecruitingInfo } from '@apis/getRecruitingInfo';

import type { ErrorResponse } from '@type/errorResponse';
import type { RecruitingResponse } from '@type/recruitingInfo';
import type { AxiosError, AxiosResponse } from 'axios';
import type { CustomError } from '@apis/instance';

const useGetRecruitingInfo = () => {
const { data, isLoading } = useQuery<
AxiosResponse<RecruitingResponse, null>,
AxiosError<ErrorResponse, null>,
AxiosResponse<RecruitingResponse, null>,
string[]
>({
const { data, isLoading } = useQuery<RecruitingResponse, CustomError, RecruitingResponse, string[]>({
queryKey: ['get-recruiting-info'],
queryFn: getRecruitingInfo,
});
Expand Down
4 changes: 2 additions & 2 deletions src/views/PasswordPage/apis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ export const sendPasswordChange = async (userInfo: PasswordRequest) => {
const { email, season, group, password, passwordCheck } = userInfo;
const res = await instance('/recruiting-auth/change/password', {
method: 'POST',
body: JSON.stringify({
body: {
email,
season,
group,
password,
passwordCheck,
}),
},
});

return res;
Expand Down
7 changes: 3 additions & 4 deletions src/views/PasswordPage/hooks/useMutateChangePassword.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { useMutation } from '@tanstack/react-query';
import { AxiosError, AxiosResponse } from 'axios';

import { sendPasswordChange } from '../apis';

import type { PasswordRequest, PasswordResponse } from '../types';
import type { ErrorResponse } from '@type/errorResponse';
import type { CustomError } from '@apis/instance';

interface MutateChangePasswordProps {
onSuccess: () => void;
}

const useMutateChangePassword = ({ onSuccess }: MutateChangePasswordProps) => {
const { mutate: changePasswordMutate, isPending: changePasswordIsPending } = useMutation<
AxiosResponse<PasswordResponse, PasswordRequest>,
AxiosError<ErrorResponse, PasswordRequest>,
PasswordResponse,
CustomError,
PasswordRequest
>({
mutationFn: (userInfo: PasswordRequest) => sendPasswordChange(userInfo),
Expand Down
4 changes: 2 additions & 2 deletions src/views/SignInPage/apis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ export const sendSignIn = async (userInfo: SignInRequest) => {
const { email, season, group, password } = userInfo;
const res = await instance('/recruiting-auth/login', {
method: 'POST',
body: JSON.stringify({
body: {
email,
season,
group,
password,
}),
},
});

return res;
Expand Down
13 changes: 4 additions & 9 deletions src/views/SignInPage/hooks/useMutateSignIn.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,24 @@ import { VALIDATION_CHECK } from '@constants/validationCheck';
import { sendSignIn } from '../apis';

import type { SignInRequest, SignInResponse } from '../types';
import type { ErrorResponse } from '@type/errorResponse';
import type { AxiosError, AxiosResponse } from 'axios';
import type { CustomError } from '@apis/instance';

interface MutateSignInProps {
finalPassConfirmEnd?: string;
onSetError: (name: string, type: string, message: string) => void;
}

const useMutateSignIn = ({ finalPassConfirmEnd, onSetError }: MutateSignInProps) => {
const { mutate: signInMutate, isPending: signInIsPending } = useMutation<
AxiosResponse<SignInResponse, SignInRequest>,
AxiosError<ErrorResponse, SignInRequest>,
SignInRequest
>({
const { mutate: signInMutate, isPending: signInIsPending } = useMutation<SignInResponse, CustomError, SignInRequest>({
mutationFn: (userInfo: SignInRequest) => sendSignIn(userInfo),
onSuccess: ({ data: { email, token } }) => {
onSuccess: ({ email, token }) => {
setUserId(email);
localStorage.setItem('soptApplyAccessToken', token);
localStorage.setItem('soptApplyAccessTokenExpiredTime', finalPassConfirmEnd || '');
window.location.reload();
},
onError(error) {
if (error.response?.status === 403) {
if (error.status === 403) {
onSetError('email', 'not-match', VALIDATION_CHECK.email.notMatchErrorText);
onSetError('password', 'not-match', VALIDATION_CHECK.password.notMatchErrorText);
}
Expand Down
4 changes: 2 additions & 2 deletions src/views/SignupPage/apis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ export const sendSignUp = async (userInfo: SignUpRequest) => {
const { email, password, passwordCheck, name, phone, season, group } = userInfo;
const res = await instance('/recruiting-auth/signup', {
method: 'POST',
body: JSON.stringify({
body: {
email,
password,
passwordCheck,
name,
phone,
season,
group,
}),
},
});

return res;
Expand Down
11 changes: 3 additions & 8 deletions src/views/SignupPage/hooks/useMutateSignUp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import { useNavigate } from 'react-router-dom';
import { sendSignUp } from '../apis';

import type { SignUpRequest, SignUpResponse } from '../types';
import type { ErrorResponse } from '@type/errorResponse';
import type { AxiosError, AxiosResponse } from 'axios';
import type { CustomError } from '@apis/instance';

interface MutateSignUpProps {
onCheckExistence: () => void;
Expand All @@ -15,18 +14,14 @@ interface MutateSignUpProps {
const useMutateSignUp = ({ onCheckExistence }: MutateSignUpProps) => {
const navigate = useNavigate();

const { mutate: signUpMutate, isPending: signUpIsPending } = useMutation<
AxiosResponse<SignUpResponse, SignUpRequest>,
AxiosError<ErrorResponse, SignUpRequest>,
SignUpRequest
>({
const { mutate: signUpMutate, isPending: signUpIsPending } = useMutation<SignUpResponse, CustomError, SignUpRequest>({
mutationFn: (userInfo: SignUpRequest) => sendSignUp(userInfo),
onSuccess: () => {
track('done-signup-apply');
navigate('/');
},
onError: (error) => {
if (error.response?.status === 400) {
if (error.status === 400) {
onCheckExistence();
}
},
Expand Down