BaşlarkenBir istemciden GraphQL sunucusuna bağlanma
Bir istemciden GraphQL sunucusuna bağlanma
Web sitesi, JavaScript çalıştıran herhangi bir tarayıcıdan GraphQL sunucusuna bağlanabilir. Buna şunlar dahildir:
- İstemci tarafı uygulamada saf JS (Vanilla JS)
- Bir framework kullanarak (Vue veya React gibi)
- Bir WordPress editör bloğu içinden
Sunucuya bağlanmak için herhangi bir GraphQL istemci kütüphanesi kullanabiliriz:
Ancak GraphQL endpoint'ine bağlanmak için harici bir JavaScript kütüphanesine gerek yoktur: aşağıda gösterildiği gibi, basit JavaScript kodu zaten yeterlidir.
Bir GraphQL endpoint'ine karşı queries çalıştırma
Bu JavaScript kodu, GraphQL sunucusuna değişkenlerle birlikte bir query gönderir ve yanıtı konsola yazdırır.
/**
* 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));
}
})();Kalıcı queries çalıştırma
Kalıcı bir query çalıştırmanın birkaç farkı vardır:
- GraphQL query göndermek gerekmez
- İşlem
POSTdeğil,GETşeklindedir - Değişkenler ve işlem adı URL'ye eklenmelidir
/**
* 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 başlığı gönderme
Bir nonce içeren bir işlem çalıştırmanız gerekiyorsa, X-WP-Nonce başlığını ekleyin.
Nonce değerinizi yazdırın:
<script>
const NONCE = '{ Print nonce value }' ;
</script>fetch çağrısının başlıklarına ekleyin:
{
headers: {
'X-WP-Nonce': `${ NONCE }`
}
}