시작하기
시작하기클라이언트에서 GraphQL 서버로 연결하기

클라이언트에서 GraphQL 서버로 연결하기

웹사이트는 JavaScript를 실행하는 모든 브라우저에서 GraphQL 서버에 연결할 수 있습니다. 여기에는 다음이 포함됩니다:

  • 클라이언트 사이드 애플리케이션의 Vanilla JS
  • 프레임워크(Vue나 React 등) 사용
  • WordPress 에디터 블록 내에서의 연결

서버에 연결하기 위해 다음을 포함한 모든 GraphQL 클라이언트 라이브러리를 사용할 수 있습니다:

그러나 GraphQL 엔드포인트에 연결하기 위해 외부 JavaScript 라이브러리가 필요하지 않습니다. 아래에서 보여주듯이 간단한 JavaScript 코드만으로도 충분합니다.

GraphQL 엔드포인트에 대한 쿼리 실행

이 JavaScript 코드는 변수가 포함된 쿼리를 GraphQL 서버에 전송하고, 응답을 콘솔에 출력합니다.

/**
 * Replace here using either:
 * - The single endpoint's URL
 * - A custom endpoint's permalink
 */
const GRAPHQL_ENDPOINT = '{ YOUR_ENDPOINT_URL }';
 
(async function () {
  const limit = 3;
  const data = {
    query: `
query GetPostsWithAuthor($limit: Int) {
  posts(pagination: { limit: $limit }) {
    id
    title
    author {
      id
      name
    }
  }
}
    `,
    variables: {
      limit: `${ limit }`
    },
  };
 
  const response = await fetch(
    GRAPHQL_ENDPOINT,
    {
      method: 'post',
      body: JSON.stringify(data),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'Content-Length': data.length,
      },
      credentials: 'include',
    }
  );
 
  /**
   * Execute the query, and await the response
   */
  const json = await response.json();
 
  /**
   * Check if the query produced errors, otherwise use the results
   */
  if (json.errors) {
    console.log(JSON.stringify(json.errors));
  } else {
    console.log(JSON.stringify(json.data));
  }
})();

퍼시스티드 쿼리 실행

퍼시스티드 쿼리 실행에는 몇 가지 차이점이 있습니다:

  • GraphQL 쿼리를 전송할 필요가 없음
  • 작업은 POST가 아닌 GET
  • 변수와 작업 이름은 URL에 추가해야 함
/**
 * Replace here using:
 * - A persisted query's permalink
 */
const GRAPHQL_PERSISTED_QUERY_PERMALINK = '{ YOUR_PERSISTED_QUERY_PERMALINK }';
 
(async function () {
  const limit = 3;
 
  /**
   * If needed, add variables in the URL
   */
  const GRAPHQL_PERSISTED_QUERY = `${ GRAPHQL_PERSISTED_QUERY_PERMALINK }?limit=${ limit }`;
 
  const response = await fetch(
    GRAPHQL_PERSISTED_QUERY,
    {
      method: 'get',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'Content-Length': data.length,
      },
      credentials: 'include',
    }
  );
 
  const json = await response.json();
  if (json.errors) {
    console.log(JSON.stringify(json.errors));
  } else {
    console.log(JSON.stringify(json.data));
  }
})();

nonce 헤더 전송

nonce를 포함한 작업을 실행해야 하는 경우 X-WP-Nonce 헤더를 추가하세요.

nonce를 출력합니다:

<script>
const NONCE = '{ Print nonce value }' ;
</script>

fetch의 헤더에 포함시킵니다:

{
  headers: {
    'X-WP-Nonce': `${ NONCE }`
  }
}