Empezando
EmpezandoConectando con el servidor GraphQL desde un cliente

Conectando con el servidor GraphQL desde un cliente

La web puede conectarse al servidor GraphQL desde cualquier navegador que ejecute JavaScript. Esto incluye:

  • JavaScript puro en la aplicación del lado del cliente
  • Usando un framework (como Vue o React)
  • Desde dentro de un bloque del editor de WordPress

Podemos usar cualquier biblioteca cliente de GraphQL para conectarnos al servidor, incluyendo:

Sin embargo, no es necesaria una biblioteca JavaScript externa para conectarse al endpoint de GraphQL: basta con código JavaScript simple, como se muestra a continuación.

Ejecutando consultas contra un endpoint GraphQL

Este código JavaScript envía una consulta con variables al servidor GraphQL, e imprime la respuesta por consola.

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

Ejecutando consultas persistidas

Ejecutar una consulta persistida tiene algunas diferencias:

  • No hay necesidad de enviar una consulta GraphQL
  • La operación es GET, no POST
  • Las variables y el nombre de la operación deben añadirse a la 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 la cabecera nonce

Si necesitas ejecutar una operación que incluya un nonce, añade la cabecera X-WP-Nonce.

Imprime tu nonce:

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

Inclúyelo en las cabeceras de fetch:

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