向编辑器中的区块提供数据
WordPress 编辑器中的内容通过(Gutenberg)区块创建,区块通过 API 从服务器获取数据。WordPress 核心使用 WP REST API,但我们也可以使用 Gato GraphQL 来驱动自己的区块。
让我们来探索区块如何从 GraphQL 服务器获取数据。
端点
由于区块在 WordPress 编辑器的上下文中使用,用户已处于登录状态,因此我们可以连接到内部 GraphQL 端点(仅在 wp-admin 内可访问),而非公开端点。
这个内部 blockEditor 端点可通过以下 URL 访问:
https://mysite.com/wp-admin/edit.php?page=gatographql&action=run_query&endpoint_group=blockEditor该端点具有预定义的配置(即不会应用插件的用户偏好设置),因此其行为是一致的。
方便的是,我们也可以引用包含端点 URL 的 JavaScript 全局变量 GATOGRAPHQL_BLOCK_EDITOR_ADMIN_ENDPOINT。
您还可以创建自己的内部端点,并为您的区块预定义所需的特定配置(启用嵌套 mutation、启用命名空间、定义可查询的 CPT,或 Schema Configuration 中可用的任何其他设置)。
或者,您可以创建 Persisted Queries 并从中(而非从端点)获取数据。请查看客户端代码需要如何适配。
通过 fetch 连接
我们可以使用标准的 fetch 方法连接到服务器。
以下 JavaScript 代码将带变量的 query 提交到 GraphQL 服务器,并将响应打印到控制台。
(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(
GATOGRAPHQL_BLOCK_EDITOR_ADMIN_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));
}
})();发送 REST nonce 请求头
如果需要执行包含 REST nonce 的操作,请添加 X-WP-Nonce 请求头。
通过 PHP 代码输出包含 nonce 的 JS 变量:
// Generate HTML in the editor:
// <script type="text/javascript">var WP_REST_NONCE = "{ Nonce value }"</script>
add_action(
'admin_print_scripts',
function(): void {
printf(
'<script type="text/javascript">var %s = "%s"</script>',
'WP_REST_NONCE',
wp_create_nonce('wp_rest')
);
}
);然后在 fetch 的请求头中包含 nonce 值:
// ...
headers: {
'X-WP-Nonce': `${ WP_REST_NONCE }`,
// ...
};通过 GraphQL 客户端库连接
您也可以使用您喜欢的 GraphQL 客户端库连接到服务器。以下是一些可选方案:
/* eslint-disable */
const { request, gql } = require(`graphql-request`)
main()
async function main() {
const query = gql`
query {
posts {
id
title
author {
id
name
}
}
}
`
const data = await request(GATOGRAPHQL_BLOCK_EDITOR_ADMIN_ENDPOINT, query)
console.log(data)
}Gato GraphQL 插件本身也通过 GraphQL 驱动其区块,使用的正是 graphql-request 库。
请查看「Schema Configuration」区块的源代码及其数据 store。