MemulaiMenghubungkan ke server GraphQL dari klien
Menghubungkan ke server GraphQL dari klien
Website dapat terhubung ke server GraphQL dari browser apa pun yang menjalankan JavaScript. Ini mencakup:
- Vanilla JS di aplikasi sisi klien
- Menggunakan framework (seperti Vue atau React)
- Dari dalam blok editor WordPress
Kita dapat menggunakan library klien GraphQL apa pun untuk terhubung ke server, termasuk:
Namun, tidak diperlukan library JavaScript eksternal untuk terhubung ke endpoint GraphQL: kode JavaScript sederhana sudah cukup, seperti yang ditunjukkan di bawah ini.
Mengeksekusi queries terhadap endpoint GraphQL
Kode JavaScript ini mengirimkan query dengan variabel ke server GraphQL, dan mencetak respons ke konsol.
/**
* 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));
}
})();Mengeksekusi persisted queries
Mengeksekusi persisted query memiliki beberapa perbedaan:
- Tidak perlu mengirimkan GraphQL query
- Operasinya adalah
GET, bukanPOST - Variabel dan nama operasi harus ditambahkan ke 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));
}
})();Mengirimkan header nonce
Jika Anda perlu mengeksekusi operasi yang menyertakan nonce, tambahkan header X-WP-Nonce.
Cetak nonce Anda:
<script>
const NONCE = '{ Print nonce value }' ;
</script>Sertakan dalam header ke fetch:
{
headers: {
'X-WP-Nonce': `${ NONCE }`
}
}