[GraphQL] GraphQL과 함께 떠나는 github 탐험

Tai Song·2022년 8월 2일
2

T-I-L

목록 보기
2/2
post-thumbnail

다양한 정보를 가져오기 위해서 여러 개의 엔드 포인트에 GET 요청을 보내야 하는 REST API와 달리, 하나의 엔드 포인트에 한 번의 쿼리 요청으로 필요한 정보를 가져올 수 있는 GraphQL.

github에서 제공하는 GraphQL explorer를 사용하면 다양한 깃헙 레포지토리 데이터를 가져오고, 가공할 수 있다!

1. GraphQL 라이브러리 설치

/* graphQL의 쿼리를 로컬 환경에서 수행할 수 있는 라이브러리를 설치한다.*/
npm install @octokit/graphql

2. GraphQL 라이브러리 임포트

/* graphQL 라이브러리를 불러온다 */
import { graphql } from "@octokit/graphql";

👉 깃허브에서 어떤 쿼리를 사용할 수 있는지는 익스플로러에서 찾아볼 수 있다.

3. 쿼리 요청 작성

! 요청 전 토큰 먼저 발급 받을 것(토큰 발급 링크).

function App() {
  const [data, setData] = useState();
  const [isLoading, setIsLoading] = useState(true)
  
  async function repo() {
    const { repository } = await graphql(
      /* 아래는 요청할 쿼리가 들어가는 영역 */
      `
        {
          repository(owner: "codestates-seb", name: "agora-states-fe") {
            discussions(first: 10) {
              edges {
                node {
                  title
                  url
                  author {
                    resourcePath
                  }
                }
              }
            }
          }
        }
      `,
      {
        headers: {
          authorization: `token /* 발급 받은 토큰 넣기 */`,
        },
      }
    );
    return repository;
  }

  useEffect(() => {
    repo()
    .then(res => {
      setData(res.discussions.edges)
      setIsLoading(false)
    })
  }, [])

  return (
    <div className="App">
      {isLoading? "loading..." : data.map((el, index) => {
        return <li key = {index}>
          <a href={el.node.url}>{el.node.title}</a>
          <span>{el.node.author.resourcePath}</span>
        </li>
      })}
    </div>
  );
}

export default App;

🧩 더 많은 사용법은 공식 문서로.

profile
Read The Fucking MDN

0개의 댓글