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

[FE] Refactor/#365 API 요청 로직 분리 및 컴포넌트 분리 #368

Merged
merged 32 commits into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
e986138
rename: 2 Depth 컴포넌트 디렉토리 구조 변경
semnil5202 Aug 22, 2023
8c2474b
refactor: 서버와 지도 GET API 요청 로직 분리
semnil5202 Aug 22, 2023
d55705d
refactor: 서버와 로그인 GET API 분리
semnil5202 Aug 22, 2023
ce98032
refactor: api 요청 로직 에러 핸들링 추가 및 명시적으로 조건문 지정
semnil5202 Aug 22, 2023
15ab15d
fix: 누락된 api 수정 적용
semnil5202 Aug 22, 2023
813abba
rename: 사용하지 않는 svg 제거 및 오타 수정
semnil5202 Aug 23, 2023
2546e27
refactor: 타입명 코드 컨벤션에 맞게 모두 변경
semnil5202 Aug 25, 2023
f941846
refactor: api get 요청 로직 커스텀 훅으로 분리
semnil5202 Aug 27, 2023
1ad8b58
feat: usePost api 요청 커스텀 훅 생성
semnil5202 Aug 27, 2023
dac9544
feat: usePut api 요청 커스텀 훅 생성
semnil5202 Aug 27, 2023
e6c0e85
feat: useDelete api 요청 커스텀 훅 생성
semnil5202 Aug 27, 2023
85090f4
remove: 사용하지 않는 페이지 컴포넌트 제거
semnil5202 Aug 27, 2023
b0225e8
fix: delete 요청을 두 번씩 날리는 오류 수정
semnil5202 Aug 27, 2023
580bfdd
refactor: Home 컴포넌트 뎁스 줄임 및 fetchGet 적용
semnil5202 Aug 27, 2023
8876235
remove: 불필요한 페이지 컴포넌트 제거
semnil5202 Aug 27, 2023
cd0efd1
refactor: bookmark 페이지 및 관련 컴포넌트 관심사 분리
semnil5202 Aug 27, 2023
d1c9fe5
rename: 불필요한 페이지 제거 및 페이지명 변경
semnil5202 Aug 27, 2023
9120741
refactor: 누락된 타입 프로퍼티 추가
semnil5202 Aug 27, 2023
73f3602
fix: 유효하지 않은 주소를 클릭 시 에러 토스트를 띄우는 기능 수정
semnil5202 Aug 27, 2023
da84f79
rename: Topic Card 컴포넌트를 담는 상위 컨테이너 컴포넌트 명 변경
semnil5202 Aug 28, 2023
d0f66dc
design: myInfo의 사용자 성명 font weight 수정
semnil5202 Aug 28, 2023
bd7f45d
style: 불필요한 import 제거 및 공백 수정
semnil5202 Aug 28, 2023
a7043b2
refactor: 중복되는 역할의 컴포넌트 제거 후 재사용
semnil5202 Aug 28, 2023
a7f7838
refactor: 잘못된 에러 메시지 수정
semnil5202 Aug 28, 2023
9387a24
design: 내가 만든 지도가 없을 경우 사용자에게 알림 문구 더 친화적으로 수정
semnil5202 Aug 28, 2023
35685c1
refactor: 중복 컴포넌트 제거 및 TopicCardList 재사용 반영
semnil5202 Aug 28, 2023
0b84692
refactor: 10m 이내로 핀이 찍힐 확률을 줄이면서 사용성을 개선할 수 있는 줌 Limit 수정
semnil5202 Aug 28, 2023
973904b
rename: 스켈레톤 컴포넌트 불규칙했던 디렉토리 구조 통일
semnil5202 Aug 28, 2023
5384aa0
rename: NotFound 페이지 컴포넌트 디렉토리 위치 조정
semnil5202 Aug 28, 2023
45b165e
refactor: usePost를 success message 대신 onSuccess 함수 받도록 변경
semnil5202 Aug 28, 2023
7d708be
refactor: 모달용 토픽 카드 컴포넌트 제거 후 기존 토픽카드에 타입 프롭 추가
semnil5202 Aug 28, 2023
95f27be
refactor: put, delete api 요청 hook interface 조정
semnil5202 Aug 29, 2023
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
32 changes: 32 additions & 0 deletions frontend/src/apiHooks/useDelete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { deleteApi } from '../apis/deleteApi';
import useToast from '../hooks/useToast';
import { ContentTypeType } from '../types/Api';

interface fetchDeleteProps {
url: string;
contentType?: ContentTypeType;
}

const useDelete = () => {
const { showToast } = useToast();

const fetchDelete = async (
{ url, contentType }: fetchDeleteProps,
errorMessage: string,
onSuccess: () => void,
) => {
try {
await deleteApi(url, contentType);

if (onSuccess) {
onSuccess();
}
} catch (e) {
showToast('error', errorMessage);
}
};

return { fetchDelete };
};

export default useDelete;
23 changes: 23 additions & 0 deletions frontend/src/apiHooks/useGet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { getApi } from '../apis/getApi';
import useToast from '../hooks/useToast';

const useGet = () => {
const { showToast } = useToast();

const fetchGet = async <T>(
url: string,
errorMessage: string,
onSuccess: (responseData: T) => void,
) => {
try {
const responseData = await getApi<T>(url);
onSuccess(responseData);
} catch (e) {
showToast('error', errorMessage);
}
};

return { fetchGet };
};

export default useGet;
35 changes: 35 additions & 0 deletions frontend/src/apiHooks/usePost.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { postApi } from '../apis/postApi';
import useToast from '../hooks/useToast';
import { ContentTypeType } from '../types/Api';

interface fetchPostProps {
url: string;
payload: {};
contentType?: ContentTypeType;
}

const usePost = () => {
const { showToast } = useToast();

const fetchPost = async (
{ url, payload, contentType }: fetchPostProps,
errorMessage: string,
onSuccess?: () => void,
) => {
try {
const responseData = await postApi(url, payload, contentType);

if (onSuccess) {
onSuccess();
}

return responseData;
} catch (e) {
showToast('error', errorMessage);
}
};

return { fetchPost };
};

export default usePost;
35 changes: 35 additions & 0 deletions frontend/src/apiHooks/usePut.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { putApi } from '../apis/putApi';
import useToast from '../hooks/useToast';
import { ContentTypeType } from '../types/Api';

interface fetchPutProps {
url: string;
payload: {};
contentType?: ContentTypeType;
}

const usePut = () => {
const { showToast } = useToast();

const fetchPut = async (
{ url, payload, contentType }: fetchPutProps,
errorMessage: string,
onSuccess?: () => void,
) => {
try {
const responseData = await putApi(url, payload, contentType);

if (onSuccess) {
onSuccess();
}

return responseData;
} catch (e) {
showToast('error', errorMessage);
}
};

return { fetchPut };
};

export default usePut;
33 changes: 27 additions & 6 deletions frontend/src/apis/deleteApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,34 @@
// : process.env.REACT_APP_API_DEFAULT_DEV;

import { DEFAULT_PROD_URL } from '../constants';
import { ContentTypeType } from '../types/Api';

export const deleteApi = async (url: string, contentType?: string) => {
await fetch(`${DEFAULT_PROD_URL + url}`, {
interface Headers {
'content-type': string;
[key: string]: string;
}

export const deleteApi = async (url: string, contentType?: ContentTypeType) => {
const apiUrl = `${DEFAULT_PROD_URL + url}`;
const userToken = localStorage.getItem('userToken');
const headers: Headers = {
'content-type': 'application/json',
};

if (userToken) {
headers['Authorization'] = `Bearer ${userToken}`;
}

if (contentType) {
headers['content-type'] = contentType;
}

const response = await fetch(apiUrl, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${localStorage.getItem('userToken') || ''}`,
'Content-Type': contentType || 'application/json',
},
headers,
});

if (response.status >= 400) {
throw new Error('[SERVER] DELETE 요청에 실패했습니다.');
}
};
24 changes: 12 additions & 12 deletions frontend/src/apis/getApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,31 @@
import { DEFAULT_PROD_URL } from '../constants';

interface Headers {
'Content-Type': string;
'content-type': string;
[key: string]: string;
}
export const getApi = async <T>(
type: 'tMap' | 'default' | 'login',
url: string,
): Promise<T> => {
const apiUrl =
type === 'tMap' || type === 'login' ? url : `${DEFAULT_PROD_URL + url}`;

export const getApi = async <T>(url: string) => {
const apiUrl = `${DEFAULT_PROD_URL + url}`;
const userToken = localStorage.getItem('userToken');
const headers: Headers = {
'Content-Type': 'application/json',
'content-type': 'application/json',
};

if (userToken) {
headers['Authorization'] = `Bearer ${userToken}`;
}

const response = await fetch(apiUrl, {
method: 'GET',
headers: headers,
headers,
});
const responseData: T = await response.json();

if (response.status >= 400) {
//todo: status 상태별로 로그인 토큰 유효 검증
throw new Error('API 요청에 실패했습니다.');
throw new Error('[SERVER] GET 요청에 실패했습니다.');
}

const responseData: T = await response.json();

return responseData;
};
16 changes: 16 additions & 0 deletions frontend/src/apis/getLoginApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const getLoginApi = async <T>(url: string) => {
const response = await fetch(url, {
method: 'GET',
headers: {
'content-type': 'application/json',
},
});

if (response.status >= 400) {
throw new Error('[KAKAO] GET 요청에 실패했습니다.');
}

const responseData: T = await response.json();

return responseData;
};
23 changes: 13 additions & 10 deletions frontend/src/apis/getMapApi.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
export const getMapApi = (url: string) =>
fetch(url, {
export const getMapApi = async <T>(url: string) => {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-type': 'application/json',
'content-type': 'application/json',
},
})
.then((data) => {
return data.json();
})
.catch((error) => {
throw new Error(`${error.message}`);
});
});

if (response.status >= 400) {
throw new Error('[MAP] GET 요청에 실패했습니다.');
}

const responseData: T = await response.json();

return responseData;
};
29 changes: 21 additions & 8 deletions frontend/src/apis/postApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,41 @@
// : process.env.REACT_APP_API_DEFAULT_DEV;

import { DEFAULT_PROD_URL } from '../constants';
import { ContentTypeType } from '../types/Api';

interface Headers {
'Content-Type': string;
'content-type': string;
[key: string]: string;
}
export const postApi = async (url: string, data?: {}, contentType?: string) => {

export const postApi = async (
url: string,
payload: {},
contentType?: ContentTypeType,
) => {
const apiUrl = `${DEFAULT_PROD_URL + url}`;
const userToken = localStorage.getItem('userToken');
const headers: Headers = {
'Content-Type': `${contentType || 'application/json'}`,
'content-type': 'application/json',
};

if (userToken) {
headers['Authorization'] = `Bearer ${userToken}`;
}

const response = await fetch(`${DEFAULT_PROD_URL + url}`, {
if (contentType) {
headers['content-type'] = contentType;
}
Comment on lines -15 to +31
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

세인 이 부분에서 'Content-Type': '${contentType || 'application/json'}'이 부분을

'content-type': 'application/json'과 if문으로 나누신 이유가 있을까요?!!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사실 취향 차이인 것 같습니다만, userToken if 블록과 통일성을 위해서 contentType도 분리해보았습니다. 로직상으로는 차이가 없지만 가독성 측면에서 좀 더 낫지 않나 싶어서 위와 같이 변경하였는데 패트릭은 어떠신가요??

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

처음에 봤을 때는 'Content-Type': ${contentType || 'application/json'}, 이 부분이 더 낫다고 생각했는데 세인의 의도를 알고나니 if문을 사용해 통일성을 가져가는 것도 좋은 것 같습니다 ! 굿!


const response = await fetch(apiUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(data),
headers,
body: JSON.stringify(payload),
});

if (response.status >= 400) {
//todo: status 상태별로 로그인 토큰 유효 검증
throw new Error('API 요청에 실패했습니다.');
throw new Error('[SERVER] POST 요청에 실패했습니다.');
}

return response;
};
23 changes: 17 additions & 6 deletions frontend/src/apis/putApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,41 @@
// : process.env.REACT_APP_API_DEFAULT_DEV;

import { DEFAULT_PROD_URL } from '../constants';
import { ContentTypeType } from '../types/Api';

interface Headers {
'Content-Type': string;
'content-type': string;
[key: string]: string;
}

export const putApi = async (
url: string,
data: { name: string; images: string[]; description: string },
data: {},
contentType?: ContentTypeType,
) => {
const apiUrl = `${DEFAULT_PROD_URL + url}`;
const userToken = localStorage.getItem('userToken');
const headers: Headers = {
'Content-Type': 'application/json',
'content-type': 'application/json',
};

if (userToken) {
headers['Authorization'] = `Bearer ${userToken}`;
}

const response = await fetch(`${DEFAULT_PROD_URL + url}`, {
if (contentType) {
headers['content-type'] = contentType;
}

const response = await fetch(apiUrl, {
method: 'PUT',
headers: headers,
headers,
body: JSON.stringify(data),
});

if (response.status >= 400) {
throw new Error('API 요청에 실패했습니다.');
throw new Error('[SERVER] PUT 요청에 실패했습니다.');
}

return response;
};
3 changes: 0 additions & 3 deletions frontend/src/assets/ModifyMyInfoIcon.svg

This file was deleted.

6 changes: 0 additions & 6 deletions frontend/src/assets/My.svg

This file was deleted.

Loading