自动化Query 解析动作
Query 解析动作
当 GraphQL 服务器解析一个 Query 时,会携带 GraphQL 响应触发以下动作钩子:
gatographql__executed_query:{$operationName}(仅在提供了要执行的 GraphQL 操作时触发)gatographql__executed_query
触发的动作钩子如下:
// Triggered only if the GraphQL operation to execute was provided
do_action(
"gatographql__executed_query:{$operationName}",
$response,
$isInternalExecution,
$query,
$variables,
);
// Triggered always
do_action(
'gatographql__executed_query',
$response,
$isInternalExecution,
$operationName,
$query,
$variables,
);传递的参数如下:
$response:PoP\Root\HttpFoundation\Response类的对象,包含 GraphQL 响应(含内容和请求头)$isInternalExecution:如果 Query 是通过 Internal GraphQL Server 执行的(例如:通过GatoGraphQL\InternalGraphQLServer\GraphQLServer类),则为true;否则(例如:通过单一端点)为false$operationName:已执行的 GraphQL 操作(仅用于第二个动作钩子;在第一个钩子中,它隐含于钩子名称中)$query:已执行的 GraphQL Query$variables:提供的 GraphQL 变量
示例
借助 Internal GraphQL Server,我们可以响应 GraphQL Query 的解析(无论是针对 Internal GraphQL Server、单一端点、自定义端点还是 persisted query 执行的),并对 Internal GraphQL Server 执行另一个 GraphQL Query。
示例工作流如下:
- 钩入 GraphQL Query 的执行,例如通过其操作名称(如
CreatePost) - 通过
GatoGraphQL\InternalGraphQLServer\GraphQLServer::executeQuery执行 mutation_sendEmail,向管理员发送通知
以下 PHP 代码链式执行了 2 个 GraphQL Query:
GraphQLServer::executeQuery(
<<<GRAPHQL
mutation CreatePost(
\$postTitle: String!,
\$postContent: String!
) {
createPost(input: {
title: \$postTitle
contentAs: { html: \$postContent }
}) {
status
errors {
__typename
...on ErrorPayload {
message
}
}
postID
}
}
GRAPHQL,
[
'postTitle' => 'New post',
'postContent' => 'Some content',
],
'CreatePost'
);
add_action(
"gatographql__executed_query:CreatePost",
function (Response $response) {
/** @var string */
$responseContent = $response->getContent();
/** @var array<string,mixed> */
$responseJSON = json_decode($responseContent, true);
$postID = $responseJSON['data']['createPost']['postID'] ?? null;
if ($postID === null) {
// Do nothing
return;
}
$post = get_post($postID);
// Execute the chained query!
GraphQLServer::executeQuery(
<<<GRAPHQL
mutation SendEmail(
\$emailSubject: String!
\$emailMessage: String!
) {
_sendEmail(
input: {
to: "admin@site.com"
subject: \$emailSubject
messageAs: {
html: \$emailMessage
}
}
) {
status
}
}
GRAPHQL,
[
'emailSubject' => sprintf(__("New post: %s"), $post->post_title),
'emailMessage' => $post->post_content,
]
);
}
);