АвтоматизацияДействие разрешения запроса
Действие разрешения запроса
Когда GraphQL-сервер разрешает запрос, он запускает следующие action hooks с GraphQL-ответом:
gatographql__executed_query:{$operationName}(только если была указана выполняемая операция GraphQL)gatographql__executed_query
Запускаемые action hooks:
// 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:true, если запрос был выполнен через Internal GraphQL Server (например: через классGatoGraphQL\InternalGraphQLServer\GraphQLServer), илиfalseв противном случае (например: через единственную конечную точку)$operationName: Выполненная операция GraphQL (только для второго action hook; в первом она неявно задана в имени хука)$query: Выполненный GraphQL-запрос$variables: Предоставленные переменные GraphQL
Примеры
Благодаря Internal GraphQL Server мы можем реагировать на разрешение GraphQL-запроса (выполненного против Internal GraphQL Server, единственной конечной точки, пользовательской конечной точки или persisted query) и выполнить другой GraphQL-запрос против Internal GraphQL Server.
Пример рабочего процесса:
- Подключиться к выполнению GraphQL-запроса, например по имени операции (например
CreatePost) - Отправить уведомление администратору, выполнив мутацию
_sendEmailчерезGatoGraphQL\InternalGraphQLServer\GraphQLServer::executeQuery
Этот PHP-код выстраивает цепочку из 2 выполнений 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,
]
);
}
);