AutomatyzacjaAkcja Rozwiązywania Query
Akcja Rozwiązywania Query
Gdy serwer GraphQL rozwiązuje query, wyzwala następujące action hooks z odpowiedzią GraphQL:
gatographql__executed_query:{$operationName}(tylko jeśli podano operację GraphQL do wykonania)gatographql__executed_query
Wyzwalane action hooks to:
// 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,
);Przekazywane parametry to:
$response: Obiekt klasyPoP\Root\HttpFoundation\Response, zawierający odpowiedź GraphQL (wraz z treścią i nagłówkami)$isInternalExecution:truejeśli query zostało wykonane za pośrednictwem Internal GraphQL Server (np. przez klasęGatoGraphQL\InternalGraphQLServer\GraphQLServer), lubfalsew przeciwnym razie (np. przez pojedynczy endpoint)$operationName: Wykonana operacja GraphQL (tylko dla drugiego action hooka; w pierwszym jest niejawna w nazwie hooka)$query: Wykonane query GraphQL$variables: Podane zmienne GraphQL
Przykłady
Dzięki Internal GraphQL Server możemy reagować na rozwiązanie query GraphQL (niezależnie od tego, czy zostało wykonane wobec Internal GraphQL Server, pojedynczego endpointu, niestandardowego endpointu czy utrwalonych queries) i wykonać kolejne query GraphQL wobec Internal GraphQL Server.
Przykładowy przepływ pracy wygląda następująco:
- Przechwycenie wykonania query GraphQL, na przykład po nazwie operacji (np.
CreatePost) - Wysłanie powiadomienia do administratora przez wykonanie mutacji
_sendEmailza pomocąGatoGraphQL\InternalGraphQLServer\GraphQLServer::executeQuery
Ten kod PHP łączy 2 wykonania queries GraphQL w łańcuch:
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,
]
);
}
);