서버 요청 로직
제가 만든 문서 편집기의 API 요청은 다음과 같이 정리됩니다.
사이드바
- 전체 문서 구조 불러오기 - GET
- 문서 생성하기 - POST
- 문서 삭제하기 - DELETE
문서 편집기
- 특정 문서의 조회하기 - GET
- 특정 문서 수정하기 - PUT
API를 요청하기 위해 request 함수를 만들어 API_END_POINT에 url, options를 이용해 그때그때 필요한 상황에 맞춰 사용할 수 있게 했고, 만약 API 처리 중 이상이 생기면 홈으로 돌아가도록 했습니다.
export const request = async (url = "", options = {}) => {
try {
const res = await fetch(`${API_END_POINT}${url}`, {
...options,
headers: {
"x-username": USERNAME,
"Content-Type": "application/json",
},
});
if (res.ok) {
return await res.json();
}
throw new Error("API 처리중 이상이 발생했습니다.");
} catch (event) {
alert(event.message);
window.location = "https://vanilla-js-editor.vercel.app/";
}
};
그리고 실제 요청하는 부분은 클래스로 만들어 필요한 부분에서 호출해 사용할 수 있도록 했습니다.
import { request } from './api.js';
export default class Data {
constructor() { }
getDocumentStructure = async () => {
const getDocumentStructure = await request('', {
method: 'GET'
})
return getDocumentStructure;
}
getDocumentContent = async (id) => {
const getDocumentStructure = await request(`/${id}`, {
method: 'GET'
})
return getDocumentStructure;
}
deleteDocumentStructure = async (id) => {
const deleteDocumentStructure = await request(`/${id}`, {
method: 'DELETE'
})
}
addDocumentStructure = async (id) => {
const addDocumentStructure = await request('', {
method: 'POST',
body: JSON.stringify({
title: "",
parent: id
})
})
return addDocumentStructure;
}
editDocument = async (id, title, content) => {
const editDocument = await request(`/${id}`, {
method: 'PUT',
body: JSON.stringify({
title: title,
content: content
})
})
return this.getDocumentStructure();
}
}
'프로젝트 > Vanilla JS 문서편집기' 카테고리의 다른 글
[Vanilla JS 문서편집기 설명 및 개선] 5. VirtualDOM처럼 렌더링하기 (1) | 2024.08.29 |
---|---|
[Vanilla JS 문서편집기 설명 및 개선] 4. 컴포넌트 템플릿 만들기 (0) | 2024.08.29 |
[Vanilla JS 문서편집기 설명 및 개선] 3. 사이드바 렌더링 최적화 및 성능 비용 절감 (0) | 2024.08.21 |
[Vanilla JS 문서편집기 설명 및 개선] 1. vite 번들러 추가 (0) | 2024.08.08 |
[23.06.27~23.07.06] 노션 클로닝 회고 (0) | 2024.08.06 |