Primeiros passos
Primeiros passosConexão ao servidor GraphQL a partir de um cliente

Conexão ao servidor GraphQL a partir de um cliente

O site pode se conectar ao servidor GraphQL a partir de qualquer navegador que execute JavaScript. Isso inclui:

  • JavaScript puro na aplicação do lado do cliente
  • Usando um framework (como Vue ou React)
  • A partir de um bloco do editor do WordPress

Podemos usar qualquer biblioteca cliente GraphQL para nos conectar ao servidor, incluindo:

No entanto, não é necessário usar uma biblioteca JavaScript externa para se conectar ao endpoint GraphQL: um código JavaScript simples já é suficiente, conforme demonstrado abaixo.

Executando queries em um endpoint GraphQL

Este código JavaScript envia uma query com variáveis ao servidor GraphQL e imprime a resposta no 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));
  }
})();

Executando queries persistidas

A execução de uma query persistida tem algumas diferenças:

  • Não é necessário enviar uma query GraphQL
  • A operação é GET, não POST
  • Variáveis e nome da operação devem ser adicionados à 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));
  }
})();

Enviando o header nonce

Se você precisar executar uma operação que inclua um nonce, adicione o header X-WP-Nonce.

Imprima seu nonce:

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

Inclua-o nos headers do fetch:

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