เริ่มต้นใช้งานการเชื่อมต่อกับเซิร์ฟเวอร์ GraphQL จากไคลเอนต์
การเชื่อมต่อกับเซิร์ฟเวอร์ GraphQL จากไคลเอนต์
เว็บไซต์สามารถเชื่อมต่อกับเซิร์ฟเวอร์ GraphQL จากเบราว์เซอร์ใดก็ได้ที่รัน JavaScript ซึ่งรวมถึง:
- Vanilla JS ในแอปพลิเคชันฝั่งไคลเอนต์
- การใช้เฟรมเวิร์ก (เช่น Vue หรือ React)
- จากภายในบล็อก WordPress editor
เราสามารถใช้ไลบรารี GraphQL client ใดก็ได้เพื่อเชื่อมต่อกับเซิร์ฟเวอร์ รวมถึง:
อย่างไรก็ตาม ไม่จำเป็นต้องใช้ไลบรารี JavaScript ภายนอกเพื่อเชื่อมต่อกับ GraphQL endpoint โค้ด JavaScript ธรรมดาก็เพียงพอแล้ว ดังที่แสดงด้านล่าง
การรัน queries กับ GraphQL endpoint
โค้ด JavaScript นี้ส่ง query พร้อมตัวแปรไปยังเซิร์ฟเวอร์ GraphQL และพิมพ์การตอบสนองไปยัง 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));
}
})();การรัน persisted queries
การรัน persisted query มีความแตกต่างบางประการ:
- ไม่จำเป็นต้องส่ง GraphQL query
- การดำเนินการเป็น
GETไม่ใช่POST - ต้องเพิ่มตัวแปรและชื่อการดำเนินการใน 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));
}
})();การส่ง nonce header
หากคุณต้องการรันการดำเนินการที่รวม nonce ให้เพิ่ม header X-WP-Nonce
พิมพ์ nonce ของคุณ:
<script>
const NONCE = '{ Print nonce value }' ;
</script>รวมไว้ใน headers สำหรับ fetch:
{
headers: {
'X-WP-Nonce': `${ NONCE }`
}
}