Bắt đầu
Bắt đầuKết nối với máy chủ GraphQL từ client

Kết nối với máy chủ GraphQL từ client

Trang web có thể kết nối với máy chủ GraphQL từ bất kỳ trình duyệt nào chạy JavaScript. Điều này bao gồm:

  • JavaScript thuần trong ứng dụng phía client
  • Sử dụng một framework (như Vue hoặc React)
  • Từ bên trong một block của trình soạn thảo WordPress

Chúng ta có thể sử dụng bất kỳ thư viện GraphQL client nào để kết nối với máy chủ, bao gồm:

Tuy nhiên, không cần thiết phải dùng thư viện JavaScript bên ngoài để kết nối với endpoint GraphQL: chỉ cần đoạn mã JavaScript đơn giản là đã đủ, như được minh họa dưới đây.

Thực thi queries trên một endpoint GraphQL

Đoạn mã JavaScript này gửi một query kèm biến đến máy chủ GraphQL và in kết quả phản hồi ra console.

/**
 * 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));
  }
})();

Thực thi persisted queries

Thực thi một persisted query có một số điểm khác biệt:

  • Không cần gửi một GraphQL query
  • Phương thức là GET, không phải POST
  • Biến và tên operation phải được thêm vào 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));
  }
})();

Gửi header nonce

Nếu bạn cần thực thi một operation bao gồm nonce, hãy thêm header X-WP-Nonce.

In nonce của bạn:

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

Đưa nó vào các header của fetch:

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