オートメーション
オートメーションクエリ解決アクション

クエリ解決アクション

GraphQLサーバーがクエリを解決すると、GraphQLレスポンスとともに以下のアクションフックがトリガーされます。

  1. gatographql__executed_query:{$operationName}(実行するGraphQL操作が指定された場合のみ)
  2. 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: クエリがInternal GraphQL Server経由で実行された場合(例:GatoGraphQL\InternalGraphQLServer\GraphQLServer クラス経由)は true、それ以外の場合(例:シングルエンドポイント経由)は false
  • $operationName: 実行されたGraphQL操作(2番目のアクションフックのみ。1番目ではフック名に暗黙的に含まれます)
  • $query: 実行されたGraphQLクエリ
  • $variables: 指定されたGraphQL変数

Internal GraphQL Server のおかげで、GraphQLクエリの解決(Internal GraphQL Server、シングルエンドポイント、カスタムエンドポイント、またはpersisted queryに対して実行されたもの)に反応し、Internal GraphQL Serverに対して別のGraphQLクエリを実行することができます。

ワークフローの例は次のとおりです。

  • GraphQLクエリの実行にフックする。たとえば操作名(CreatePost など)によって
  • GatoGraphQL\InternalGraphQLServer\GraphQLServer::executeQuery を通じてミューテーション _sendEmail を実行し、管理者に通知を送信する

この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,
      ]
    );
  }
);