노션 (자바스크립트) 클론 코딩 (5) api 연결해서 글 불러오기

2024. 11. 18. 15:57프로젝트

728x90

지금부터 더미데이터로 기능을 구현했던걸 api를 받아와서 구현하겠습니다.

먼저 api를 알아보기 이전에 사용법을 알아보도록 하겠습니다.

그다음 postman을 통해서 요청 연습을 해보겠습니다.

 

API 사용법

1. 기본사항

모든 API에는 headers에 아래의 값을 넣어야 합니다. header에 해당 값이 누락이 되면 API 호출에 실패합니다.

'x-username': '다른 사람과 겹치지 않는 고유한 이름'

2. Root Documents 가져오기

전체 Document의 구조를 트리 형태로 가져옵니다. Response의 형태는 아래와 같습니다.

[
  {
    "id": 1, // Document id
    "title": "노션을 만들자", // Document title
    "documents": [
      {
        "id": 2,
        "title": "블라블라",
        "documents": [
          {
            "id": 3,
            "title": "함냐함냐",
            "documents": []
          }
        ]
      }
    ]
  },
  {
    "id": 4,
    "title": "hello!",
    "documents": []
  }
]

3. 특정 Document의 content 조회하기

Response의 형태는 아래와 같습니다.

{
  "id": 1,
  "title": "노션을 만들자",
  "content": "즐거운 자바스크립트의 세계!",
  "documents": [
    {
      "id": 2,
      "title": "",
      "createdAt": "",
      "updatedAt": ""
    }
  ],
  "createdAt": "",
  "updatedAt": ""
}

4. Document 생성하기

request body에 JSON 형태로 아래처럼 값을 넣어야 합니다.

{
  "title": "문서 제목",
  // parent가 null이면 루트 Document가 됩니다.
  // 특정 Document에 속하게 하려면 parent에
  // 해당 Document id를 넣으세요.
  "parent": null
}

생성에 성공하면 reponse에 아래처럼 생성된 결과를 내려줍니다.

{
  "id": 6,
  "title": "문서 제목",
  "createdAt": "생성된 날짜",
  "updatedAt": "수정된 날짜"
}

5. 특정 Document 수정하기

request body에 수정할 내용을 JSON 형태로 넣으면 됩니다.

{
  "title": "제목 수정",
  "content": "내용 수정"
}

6. 특정 Document 삭제하기

documentId에 해당하는 Document를 삭제합니다.
만약 하위 documents가 있는 document를 삭제한 경우, 하위 documents 등은 상위 document가 없어지므로 root document로 인식됩니다.


https://www.postman.com/

 

Postman: The World's Leading API Platform | Sign Up for Free

Accelerate API development with Postman's all-in-one platform. Streamline collaboration and simplify the API lifecycle for faster, better results. Learn more.

www.postman.com

 

 

api를 관리하기위해서는 utils폴더를 만들고 안에 api.js 를 만들어주도록 하겠습니다.

 

api.js

export const API_END_POINT = `https://mwu1.notion.edu-api.programmers.co.kr/documents`

export const request = async () => {
    try {
        const response = await fetch(API_END_POINT, {
            headers: {
                'x-username': 'dongwok',
                'content-Type': 'application/json',
            },
        })
        if (response.ok) {
            return response.json()
        }
        throw new Error('API 요청 에러')
    } catch (e) {
        console.log(e.message)
    }
}

 

request 함수는 API 요청을 보내고 응답 데이터를 처리하는 역할을 합니다.

fetch는 JavaScript에서 HTTP 요청을 보내는 표준 함수입니다.

첫 번째 인자로 요청 URL을 받고, 두 번째 인자로 옵션 객체를 받습니다.

여기서는 headers 옵션이 설정되어 있으며, 두 가지 헤더를 포함하고 있습니다

'x- username ': 'dongwok': API 요청을 보낸 사용자의 정보를 나타내는 커스텀 헤더

'content-Type': 'application/json': 요청 데이터의 형식이 JSON임을 나타냅니다.

 

데이터들을 확인하기 위해 App.js에서 

 setTimeout(async () => {
        const a = await request()
        console.log(a)
    }, 1000)

 

 

를 추가하여 데이터들을 확인 할 수 있습니다.

 

데이터가 없으면 postman으로 데이터들을 넣고 확인하시면 됩니다.

 

그다음 SidebarPage에서

this.setState = async () => {
        const documentList = await request()
        this.state = documentList
        this.render()
    }

데이터를 동적으로 가져와 상태를 업데이트하고 재렌더링합니다.

render() 함수로 바꿔준다

this.render = () => {
        $page.innerHTML = `
        <ul>
            ${this.state
                .map(
                    (document) =>
                        `<li class="dataList">📄 ${document.title}
                        <button class="addBtn">➕</button>
                        <button class="delBtn">🗑️</button>
                    </li>
                    ${
                        document.documents.length > 0
                            ? `<ul> ${this.createTreeView(
                                  document.documents
                              )}</ul>`
                            : ''
                    }
                    `
                )

                .join('')}
        </ul>
    `
    }
    this.render()

DOM 업데이트를 명확하게 분리하고 관리하기 위함입니다.

이 함수는 SidebarPage 컴포넌트의 UI를 현재 상태(this.state)에 따라 동적으로 업데이트하는 역할을 합니다.

 

  • 상태가 업데이트될 때마다 UI를 다시 그려야 합니다.
  • render() 함수는 상태(this.state)를 기반으로 DOM을 재생성하는 독립적인 책임을 가진 함수로, 코드의 가독성과 유지보수성을 높입니다.
  • 예를 들어, 데이터를 변경하거나 API에서 새 데이터를 받아왔을 때(setState 호출), render()를 호출해 UI를 동기화합니다.