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

chore: Axios 추가 #12

Merged
merged 4 commits into from
Mar 24, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"no-param-reassign": "off",
"new-cap": "off",
"class-methods-use-this": "off",
"no-unused-vars": "off"
"no-unused-vars": "off",
"import/no-extraneous-dependencies": "off"
}
}
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ Javascript로 [toss.tech](https://toss.tech) 사이트를 구현하고, 그 과
git clone https://github.com/f-lab-edu/toss-tech-route
npm install
npm run start

# http://localhost:8080 에서 확인 가능합니다.
```
### Script
```bash
Expand All @@ -36,7 +38,7 @@ npm run prettier:check: prettier를 활용하여 코드컨벤션을 확인해요
### 구현 내용을 리뷰어에게 명확하게 전달하려고 고민했습니다.
1. 개발 순서를 세부적으로 계획하고, [issues](https://github.com/f-lab-edu/toss-tech-router/issues)에 등록하여 진행했습니다.
2. [PR 템플릿](https://github.com/f-lab-edu/toss-tech-router/blob/main/.github/PULL_REQUEST_TEMPLATE.md)을 사용하여 리뷰어가 이해하기 쉽게 구현 내용을 전달했습니다.
3. [코드리뷰](https://github.com/f-lab-edu/toss-tech-router/pull/6)에 작성한 [위키](https://github.com/f-lab-edu/toss-tech-router/wiki)를 첨부하여, 구현 내용을 상세하게 전달했습니다.
3. [코드리뷰](https://github.com/f-lab-edu/toss-tech-router/pull/10)에 작성한 [위키](https://github.com/f-lab-edu/toss-tech-router/wiki)를 첨부하여, 구현 내용을 상세하게 전달했습니다.
### 코드의 모듈화와 일관성을 유지하기 위해 노력했습니다.
1. 프로젝트 구조를 lib와 ui로 나누어 폴더 구조를 명확하게 구조화 했습니다.
2. 하드코딩을 지양하고, 재사용 가능한 코드는 모듈화하여 관리했습니다.
Expand Down
55 changes: 55 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@
},
"devDependencies": {
"@babel/core": "^7.21.3",
"@babel/plugin-transform-modules-commonjs": "^7.21.2",
"@babel/plugin-transform-runtime": "^7.21.0",
"@babel/preset-env": "^7.20.2",
"axios": "^1.3.4",
"babel-loader": "^9.1.2",
"css-loader": "^6.7.3",
"eslint": "^8.35.0",
Expand All @@ -39,12 +42,10 @@
"prettier": "^2.8.4",
"style-loader": "^3.3.1",
"webpack": "^5.76.0",
"webpack-cli": "^5.0.1",
"@babel/plugin-transform-modules-commonjs": "^7.21.2",
"@babel/plugin-transform-runtime": "^7.21.0"
"webpack-cli": "^5.0.1"
},
"lint-staged": {
"**/*.{js,html,css,json,yaml,md}": "npm run prettier:check",
"**/*.{js,html,css,json}": "npm run prettier:check",
"**/*.{js}": "npm run lint"
},
"msw": {
Expand Down
12 changes: 6 additions & 6 deletions src/lib/api/article.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ import { API_URL } from '../utils/constant';

export const apiGetArticleList = async () => {
try {
const response = await request({ url: API_URL.ARTICLES });
return response;
const response = await request.get(API_URL.ARTICLES);
return response.data;
} catch (error) {
return { error: error.message };
throw new Error(error);
Copy link
Collaborator

Choose a reason for hiding this comment

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

P3: 이런느낌으로 에러를 확장해서 쓰실 수 있어요! 추후에 센트리 설계하실때 입맛에 맞게 변경하실 수 있을거에요

class CustomError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'SomeThing Error';
  }
}

Copy link
Member Author

Choose a reason for hiding this comment

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

CustomError는 추가해보았는데, 아직 센트리를 반영하면서 어떤식으로 변경되는지는 감이 잘 오질 않네요.
센트리를 반영해보면서 더 고민해보도록 하겠습니다! 🙂

}
};

export const apiGetArticleDetail = async (id) => {
try {
const response = await request({ url: `${API_URL.ARTICLE_DETAIL}/${id}` });
return response;
const response = await request.get(`${API_URL.ARTICLE_DETAIL}/${id}`);
return response.data;
} catch (error) {
return { error: error.message };
throw new Error(error);
}
};
37 changes: 23 additions & 14 deletions src/lib/api/index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
const request = async ({
url,
options = {
method: 'GET',
},
}) => {
const response = await fetch(url, options);
import axios from 'axios';

const instance = axios.create({
baseURL: '/',
});

if (!response.ok) {
const error = await response.json();
throw new Error(`서버의 응답이 올바르지 않습니다. (${response.status}): ${error.message}`);
}
instance.interceptors.request.use(
(config) => {
return config;
},
(error) => {
return Promise.reject(error);
},
);

return response.json();
};
instance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
Copy link
Collaborator

@leeyun1533 leeyun1533 Mar 21, 2023

Choose a reason for hiding this comment

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

P2: handlerErrorResponse 라는 함수에서 처리하시면 어떨까요?
그리고, 만약에 axios에러에서 response값이 없는 에러가 발생하게 된다면 전체 앱이 뻗을 수도 있을 것 같아요.
옵셔널 체이닝으로 관련 에러 방지 해주시면 좋을 것 같아요

Copy link
Member Author

Choose a reason for hiding this comment

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

export const handleErrorResponse = (error) => {
  if (error instanceof CustomError) {
    console.log('CustomError: ', error.name, error.message);
    return;
  }
  console.log('Error: ', error?.message);
};

리뷰 주신 내용으로 handlerErrorResponse 함수 구현해보았습니다.

const errorMessage = error.response ? `서버 응답이 올바르지 않습니다. ${error.response.status}: ${error.response.data.message}` : error.message;
return Promise.reject(new Error(errorMessage));
},
);

export default request;
export default instance;