Aan de slagVerbinding maken met de GraphQL-server vanuit een client
Verbinding maken met de GraphQL-server vanuit een client
De website kan verbinding maken met de GraphQL-server vanuit elke browser die JavaScript ondersteunt. Dit omvat:
- Vanilla JS in de client-side applicatie
- Het gebruik van een framework (zoals Vue of React)
- Vanuit een WordPress-editorblok
Je kunt elke GraphQL-clientbibliotheek gebruiken om verbinding te maken met de server, waaronder:
Er is echter geen externe JavaScript-bibliotheek nodig om verbinding te maken met het GraphQL-endpoint: eenvoudige JavaScript-code volstaat al, zoals hieronder wordt gedemonstreerd.
Queries uitvoeren tegen een GraphQL-endpoint
Deze JavaScript-code stuurt een query met variabelen naar de GraphQL-server en toont het antwoord in de 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));
}
})();Bewaarde queries uitvoeren
Het uitvoeren van een bewaarde query verschilt op een aantal punten:
- Er hoeft geen GraphQL-query te worden meegestuurd
- De methode is
GET, nietPOST - Variabelen en de naam van de operatie moeten aan de URL worden toegevoegd
/**
* 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));
}
})();Nonce-header meesturen
Als je een operatie moet uitvoeren met een nonce, voeg dan de header X-WP-Nonce toe.
Geef je nonce weer:
<script>
const NONCE = '{ Print nonce value }' ;
</script>Voeg deze toe aan de headers van fetch:
{
headers: {
'X-WP-Nonce': `${ NONCE }`
}
}