Automação
AutomaçãoAção de Resolução de Query

Ação de Resolução de Query

Quando o servidor GraphQL resolve uma query, ele dispara os seguintes action hooks com a resposta GraphQL:

  1. gatographql__executed_query:{$operationName} (somente se a operação GraphQL a executar foi fornecida)
  2. gatographql__executed_query

Os action hooks que são disparados são:

// 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,
);

Os parâmetros passados são:

  • $response: Um objeto da classe PoP\Root\HttpFoundation\Response, contendo a resposta GraphQL (incluindo conteúdo e headers)
  • $isInternalExecution: true se a query foi executada via Internal GraphQL Server (ex.: via classe GatoGraphQL\InternalGraphQLServer\GraphQLServer), ou false caso contrário (ex.: via endpoint único)
  • $operationName: Operação GraphQL executada (apenas para o segundo action hook; no primeiro, está implícita no nome do hook)
  • $query: Query GraphQL executada
  • $variables: Variáveis GraphQL fornecidas

Exemplos

Graças ao Internal GraphQL Server, podemos reagir à resolução de uma query GraphQL (seja executada contra o Internal GraphQL Server, endpoint único, endpoint personalizado ou queries persistidas), e executar outra query GraphQL contra o Internal GraphQL Server.

Um exemplo de fluxo de trabalho é:

  • Interceptar a execução de uma query GraphQL, por exemplo pelo nome da operação (como CreatePost)
  • Enviar uma notificação ao administrador, executando a mutation _sendEmail via GatoGraphQL\InternalGraphQLServer\GraphQLServer::executeQuery

Este código PHP encadeia 2 execuções de queries 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,
      ]
    );
  }
);