Skip to content

Commit

Permalink
Merge pull request #1 from AnOldStory/main
Browse files Browse the repository at this point in the history
feat: API - axios & interceptor
  • Loading branch information
AnOldStory authored Apr 24, 2022
2 parents e444549 + 62448f5 commit 624de26
Show file tree
Hide file tree
Showing 7 changed files with 195 additions and 2 deletions.
16 changes: 14 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
{
"extends": ["react-app", "eslint:recommended", "plugin:prettier/recommended"]
}
"extends": [
"react-app",
"eslint:recommended",
"plugin:prettier/recommended"
],
"rules": {
"prettier/prettier": [
"error",
{
"endOfLine": "auto"
}
]
}
}
17 changes: 17 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^13.5.0",
"axios": "^0.26.1",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "5.0.1",
Expand Down
6 changes: 6 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import WantedList from './components/WantedList';
// 이미지는 추후 백엔드/CDN에서 이미지 주소를 전달 받아야.
import coffee from './assets/img/coffee.png';
import kSoup from './assets/img/k-soup.png';
// import { useEffect } from 'react';

// import Api from './api/Api';

const tempOriginal = [
{
Expand Down Expand Up @@ -45,6 +48,9 @@ const tempWantedListData = [
];

function App() {
// useEffect(() => {
// data = await Api.getCards(); <- 이런거 부르면됩니다.
// }, []);
return (
<div className="App">
<WantedList list={tempWantedListData} />
Expand Down
96 changes: 96 additions & 0 deletions src/api/Api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import Interceptor from './Interceptor';
import CONFIG from './config';

class Api {
/**
* User Login
* @param {string} redirect - url
* @return {Object} response
* @example
* ``` json
* {
* "id": "UUID",
* "dateTime": "datetime",
* "success": true,
* "response": "https://github.com/login/oauth/authorize?client_id=0c696e3a1df74b0acf03&redirect_uri=http://localhost:8080/api/oauth2/code/github?redirect=http://localhost:3000",
* "error": null
* }
* ```
*/
signin() {
return new Promise((resolve, reject) => {
Interceptor.getInstance()
.get(CONFIG.API_SERVER + '/authenticate/github', {
params: { redirect: CONFIG.BASE_URL },
})
.then((res) => res.data)
.then((res) => {
if (!res.error) resolve(res.data);
throw new Error(res.error);
})
.catch((e) => reject(e));
});
}

/**
* get Information of Cards
* @param {Date} required_date - required_date of cards
* @return {Object} response
* @example
* ``` json
* {
* "dateTime": "datetime",
* "success": true,
* "response": [{
* "제목": "string",
* "장소(optional)": "string",
* "약속시간": "datetime",
* "종류": "enum(밥|커피|술)",
* "모집인원": "number",
* "모집상태": "enum",
* }],
* "error": null
* }
* ```
*/
getCards(required_date = new Date()) {
return new Promise((resolve, reject) => {
Interceptor.getInstance()
.get(CONFIG.API_SERVER + '/cards', {
params: { date: required_date },
})
.then((res) => res.data)
.then((res) => {
if (!res.error) resolve(res.data);
throw new Error(res.error);
})
.catch((e) => reject(e));
});
}

// authenticated zone below
// getStat(survey_id) {
// return new Promise((resolve, reject) => {
// Interceptor.getInstance()
// .post(CONFIG.API_SERVER + '/result/stats', survey_id, authHeader({}))
// .then((res) => resolve(res.data))
// .catch(reject);
// });
// }
}

export default new Api();

// /*
// {headers: authHeader()}
// Record<string, string>
// */
// function authHeader(Iany) {
// const tokenStr = localStorage.getItem('accessToken');
// return tokenStr
// ? {
// headers: { 'x-access-token': tokenStr },
// ...Iany,
// }
// : { ...Iany };
// }
55 changes: 55 additions & 0 deletions src/api/Interceptor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import axios from 'axios';

import CONFIG from './config';

const baseURL = CONFIG.API_SERVER;

/**
* Event Logger for API
*/
class Interceptor {
instance;

constructor() {
this.instance = axios.create({
baseURL,
});

this.instance = this.setupInterceptorsTo(this.instance);
}

getInstance() {
return this.instance;
}

onRequest = (config) => {
console.info(`[request] [${JSON.stringify(config)}]`);
return config;
};

onRequestError = (error) => {
console.error(`[request error] [${JSON.stringify(error)}]`);
return Promise.reject(error);
};

onResponse = (response) => {
console.info(`[response] [${JSON.stringify(response)}]`);
return response;
};

onResponseError = (error) => {
console.error(`[response error] [${JSON.stringify(error)}]`);
return Promise.reject(error);
};

setupInterceptorsTo(axiosInstance) {
axiosInstance.interceptors.request.use(this.onRequest, this.onRequestError);
axiosInstance.interceptors.response.use(
this.onResponse,
this.onResponseError,
);
return axiosInstance;
}
}

export default new Interceptor();
6 changes: 6 additions & 0 deletions src/api/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const config = {
API_SERVER: 'http://localhost:3000/api', // api server url
BASE_URL: 'http://localhost:3000', // production url
};

export default config;

0 comments on commit 624de26

Please sign in to comment.