Démarrage
DémarrageConnexion au serveur GraphQL depuis un client

Connexion au serveur GraphQL depuis un client

Le site web peut se connecter au serveur GraphQL depuis n'importe quel navigateur exécutant JavaScript. Cela inclut :

  • JavaScript pur dans l'application côté client
  • En utilisant un framework (comme Vue ou React)
  • Depuis l'intérieur d'un bloc de l'éditeur WordPress

Nous pouvons utiliser n'importe quelle bibliothèque cliente GraphQL pour nous connecter au serveur, notamment :

Cependant, il n'est pas nécessaire d'utiliser une bibliothèque JavaScript externe pour se connecter à l'endpoint GraphQL : un simple code JavaScript suffit, comme démontré ci-dessous.

Exécution de requêtes contre un endpoint GraphQL

Ce code JavaScript soumet une requête avec des variables au serveur GraphQL, et affiche la réponse dans la 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));
  }
})();

Exécution de requêtes persistées

L'exécution d'une requête persistée présente quelques différences :

  • Il n'est pas nécessaire de soumettre une requête GraphQL
  • L'opération est GET, pas POST
  • Les variables et le nom de l'opération doivent être ajoutés à l'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));
  }
})();

Envoi de l'en-tête nonce

Si vous devez exécuter une opération incluant un nonce, ajoutez l'en-tête X-WP-Nonce.

Affichez votre nonce :

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

Incluez-le dans les en-têtes de fetch :

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