Primi passi
Primi passiConnessione al server GraphQL da un client

Connessione al server GraphQL da un client

Il sito web può connettersi al server GraphQL da qualsiasi browser che esegue JavaScript. Questo include:

  • JavaScript puro nell'applicazione lato client
  • Utilizzando un framework (come Vue o React)
  • Dall'interno di un blocco dell'editor di WordPress

Possiamo utilizzare qualsiasi libreria client GraphQL per connetterci al server, tra cui:

Tuttavia, non è necessario utilizzare una libreria JavaScript esterna per connettersi all'endpoint GraphQL: un semplice codice JavaScript è già sufficiente, come dimostrato di seguito.

Esecuzione di queries su un endpoint GraphQL

Questo codice JavaScript invia una query con variabili al server GraphQL e stampa la risposta nella 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));
  }
})();

Esecuzione di queries persistite

L'esecuzione di una query persistita presenta alcune differenze:

  • Non è necessario inviare una query GraphQL
  • L'operazione è GET, non POST
  • Le variabili e il nome dell'operazione devono essere aggiunti all'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));
  }
})();

Invio dell'header nonce

Se devi eseguire un'operazione che include un nonce, aggiungi l'header X-WP-Nonce.

Stampa il tuo nonce:

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

Includilo negli header di fetch:

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