React ํ๋ก์ ํธ์์ ์กฐ์ง๋/๊ตฌ์ฑ์ ๊ฐ์ ๋๋ฏธ ๋ฐ์ดํฐ๋ฅผ mockData.ts
๋ก ๊ด๋ฆฌํ๊ณ ์๋ค๋ฉด,
์ค์ API ์๋ฒ์ ์ฐ๊ฒฐ๋ ๋ ์ฝ๋๋ฅผ ๋๊ฑฐ ๋ฏ์ด๊ณ ์น์ง ์๊ณ ๋ "๊ทธ๋๋ก ์ ํ"ํ ์ ์๋ ๊ตฌ์กฐ๋ฅผ ๋ง๋ค์ด๋ ์ ์์ต๋๋ค.
mockData.ts
์ ์๋ ๋ฐ์ดํฐ๋ฅผ ์ค์ API์ฒ๋ผ axios.get()
์ผ๋ก ๋ถ๋ฌ์ค๋ ๋ฐฉ์์ผ๋ก ์ฒ๋ฆฌ
// api/apiClient.ts
import axios from 'axios';
const BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:3000';
const apiClient = axios.create({
baseURL: BASE_URL,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
timeout: 15000
});
export default apiClient;
.env.local
:
REACT_APP_API_BASE_URL=https://mock.domain.com:443
axios-mock-adapter
)
npm install axios-mock-adapter
// api/mock/setupMockApi.ts
import MockAdapter from 'axios-mock-adapter';
import apiClient from '../apiClient';
import { initialMembers } from '@/mock/mockData';
export function setupMockApi() {
const mock = new MockAdapter(apiClient, { delayResponse: 300 });
mock.onGet('//{ํ๋ก์ ํธ๋ช
}/rest/getCpnOrgEmpList.do').reply((config) => {
const { cpnId } = config.params;
if (cpnId === 1) {
const allMembers = Object.values(initialMembers).flat().map((m, index) => ({
userId: index + 1,
userNm: m.name,
position: 1,
deptNm: '',
deptId: 0,
parentId: 0,
macId: '',
osId: ''
}));
return [200, {
pscd: 'OK',
pcsRsltMsg: '์กฐ์ง๋ ์กฐํ ์ฑ๊ณต',
Data: allMembers
}];
}
return [200, {
pscd: 'FAIL',
pcsRsltMsg: 'ํด๋น ํ์ฌ ์์',
Data: []
}];
});
}
// App.tsx or main.ts
import { setupMockApi } from '@/api/mock/setupMockApi';
if (process.env.NODE_ENV === 'development') {
setupMockApi();
}
// api/getCpnOrgEmpList.ts
import apiClient from './apiClient';
import { ApiResponse } from './apiTemplates';
export interface GetCpnOrgEmpParams {
userId: number;
cpnId: number;
}
export interface CpnOrgEmp {
userId: number;
userNm: string;
position: number;
deptNm: string;
deptId: number;
parentId: number;
macId: string;
osId: string;
}
export const getCpnOrgEmpList = async (
params: GetCpnOrgEmpParams
): Promise<ApiResponse<CpnOrgEmp[]>> => {
try {
const res = await apiClient.get('/{ํ๋ก์ ํธ๋ช
}/rest/getCpnOrgEmpList.do', { params });
return res.data;
} catch (e) {
return {
pscd: 'ERR_500',
pcsRsltMsg: '์๋ฒ ์ฐ๊ฒฐ ์คํจ'
};
}
};
useEffect(() => {
const fetchData = async () => {
const res = await getCpnOrgEmpList({ userId: 1, cpnId: 1 });
if (res.pscd === 'OK' && res.Data) {
console.log('์๋ต๋ฐ์ ๊ตฌ์ฑ์', res.Data);
} else {
console.error('API ์คํจ:', res.pcsRsltMsg);
}
};
fetchData();
}, []);
์ง๊ธ ๊ตฌ์กฐ๋ ์ค์ API๊ฐ ์๊ธฐ๋๋ผ๋ mock ์ค์ ๋ง ์ ๊ฑฐํ๋ฉด ์๋ฒฝํ๊ฒ ์ฐ๋๋ฉ๋๋ค.
๋ณ๊ฒฝ ์ | ๋ณ๊ฒฝ ํ |
---|---|
setupMockApi(); | โ ์ฃผ์ ์ฒ๋ฆฌ |
axios.get(...) | โ ๊ทธ๋๋ก ์ ์ง |
useEffect ํธ์ถ ๋ก์ง | โ ๊ทธ๋๋ก ์ ์ง |
mockData.ts | โ ์ฌ์ฉ ์ ํด๋ ๋จ |
// setupMockApi(); ๐ ์ด ํ ์ค๋ง ์ ๊ฑฐ!
์ด ๊ตฌ์กฐ๋ ๋ค์๊ณผ ๊ฐ์ ๊ฒฝ์ฐ์ ๋งค์ฐ ์ ํฉํฉ๋๋ค: