Tự động hóaHành Động Giải Quyết Query
Hành Động Giải Quyết Query
Khi máy chủ GraphQL giải quyết một query, nó kích hoạt các action hook sau đây cùng với phản hồi GraphQL:
gatographql__executed_query:{$operationName}(chỉ khi thao tác GraphQL cần thực thi được cung cấp)gatographql__executed_query
Các action hook được kích hoạt là:
// 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,
);Các tham số được truyền vào là:
$response: Một đối tượng của lớpPoP\Root\HttpFoundation\Response, chứa phản hồi GraphQL (bao gồm nội dung và các header)$isInternalExecution:truenếu query được thực thi thông qua Internal GraphQL Server (ví dụ: qua lớpGatoGraphQL\InternalGraphQLServer\GraphQLServer), hoặcfalsetrong trường hợp ngược lại (ví dụ: qua single endpoint)$operationName: Thao tác GraphQL đã được thực thi (chỉ dành cho action hook thứ hai; ở hook thứ nhất, nó được ngầm hiểu qua tên hook)$query: Query GraphQL đã được thực thi$variables: Các biến GraphQL đã được cung cấp
Ví dụ
Nhờ vào Internal GraphQL Server, chúng ta có thể phản ứng với việc giải quyết một query GraphQL (dù được thực thi qua Internal GraphQL Server, single endpoint, custom endpoint hay persisted query), và thực thi một query GraphQL khác trên Internal GraphQL Server.
Một ví dụ về quy trình làm việc là:
- Hook vào việc thực thi một query GraphQL, chẳng hạn theo tên thao tác của nó (như
CreatePost) - Gửi thông báo đến quản trị viên, bằng cách thực thi mutation
_sendEmailquaGatoGraphQL\InternalGraphQLServer\GraphQLServer::executeQuery
Đoạn mã PHP này nối tiếp 2 lần thực thi query GraphQL:
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,
]
);
}
);