const BASE_URL = 'https://kdt-frontend.programmers.co.kr/documents';
const request = async (url, options = {}) => {
try {
const res = await fetch(`${BASE_URL}${url}`, {
...options,
headers: {
'Content-Type': 'application/json',
'x-username': 'joohyeongjin',
},
});
if (res.ok) {
return await res.json(); // await로 무조건 반환하는 방법은 좋지 않음. 프로미스로 넘겨서 all을 사용하는 비동기 제어 방식으로 사용할 수 있기에!
}
throw new Error('API 처리 중 오류가 발생하였습니다!');
} catch (e) {
console.log(e.message);
history.replaceState(null, null, '/404');
window.location = `${window.location.origin}/404`;
}
};
const createDocument = async document => {
return await request(
'',
{ method: 'POST', body: JSON.stringify(document) }
);
};
const readDocuments = async id => {
const url = id ? `/${id}` : '';
return await request(
url,
{ method: 'GET' }
);
};
const updateDocument = async (id, document) => {
return await request(
`/${id}`,
{ method: 'PUT', body: JSON.stringify(document) }
);
};
const deleteDocument = async id => {
return await request(
`/${id}`,
{ method: 'DELETE' }
);
};
export { createDocument, readDocuments, updateDocument, deleteDocument };
api.js (형진님 코드 https://github.com/prgrms-fe-devcourse/FEDC2-4_Project_Notion_VanillaJS/pull/55/files#diff-4247da80059f922e2248683cec9911d57fda8c74e332b8f664db787d45892081)
개선, API 모듈화
const BASE_URL = 'https://kdt-frontend.programmers.co.kr/documents';
const request = async (url, options = {}) => {
try {
if ("body" in options) {
options.body = JSON.stringify(options.body);
}
const res = await fetch(`${BASE_URL}${url}`, {
...options,
headers: {
'Content-Type': 'application/json',
'x-username': 'joohyeongjin',
},
});
if (res.ok) {
return res.json();
}
throw new Error('API 처리 중 오류가 발생하였습니다!');
} catch (e) {
console.log(e.message);
history.replaceState(null, null, '/404');
window.location = `${window.location.origin}/404`;
}
};
// api 모듈화👍
// api 명세를 보지 않고 작업할 수 있음👍👍
const api = {
createDocument: async document => {
return request(
'',
{ method: 'POST', body: JSON.stringify(document) }
);
},
readDocuments: async id => {
const url = id ? `/${id}` : '';
return request(
url,
{ method: 'GET' }
);
}
},
updateDocument: async (id, document) => {
return request(
`/${id}`,
{ method: 'PUT', body: document }
);
},
deleteDocument: async id => {
return request(
`/${id}`,
{ method: 'DELETE' }
);
}
}
export default api;