はじめにクライアントからGraphQLサーバーへの接続
クライアントからGraphQLサーバーへの接続
WebサイトはJavaScriptを実行する任意のブラウザからGraphQLサーバーに接続できます。これには以下が含まれます:
- クライアントサイドアプリケーションのVanilla JS
- フレームワーク(VueやReactなど)の使用
- WordPressエディターブロック内からの接続
サーバーへの接続には、以下を含む任意のGraphQLクライアントライブラリを使用できます:
ただし、GraphQLエンドポイントに接続するために外部のJavaScriptライブラリは必要ありません。以下に示すように、シンプルなJavaScriptコードで十分です。
GraphQLエンドポイントに対するクエリの実行
このJavaScriptコードは、変数を含むクエリをGraphQLサーバーに送信し、レスポンスをコンソールに出力します。
/**
* 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));
}
})();パーシストクエリの実行
パーシストクエリの実行にはいくつかの違いがあります:
- GraphQLクエリを送信する必要がない
- 操作は
POSTではなくGET - 変数と操作名は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ヘッダーの送信
nonceを含む操作を実行する必要がある場合は、X-WP-Nonceヘッダーを追加してください。
nonceを出力します:
<script>
const NONCE = '{ Print nonce value }' ;
</script>fetchのヘッダーに含めます:
{
headers: {
'X-WP-Nonce': `${ NONCE }`
}
}