diff --git a/src/Utils/QueryAnalyzer.php b/src/Utils/QueryAnalyzer.php index 50fba4b4b2..1ecc7ea920 100644 --- a/src/Utils/QueryAnalyzer.php +++ b/src/Utils/QueryAnalyzer.php @@ -34,6 +34,13 @@ class QueryAnalyzer { * @var \GraphQL\Type\Schema */ protected $schema; + + /** + * Indicates whether any nodes have been resolved. + * + * @var bool + */ + private static $nodes_resolved = false; /** * Types that are referenced in the query @@ -603,6 +610,7 @@ public function set_query_models( ?Schema $schema, ?string $query ): array { */ public function track_nodes( $model ) { if ( isset( $model->id ) && in_array( get_class( $model ), $this->get_query_models(), true ) ) { + self::$nodes_resolved = true; // Is this model type part of the requested/returned data in the asked for query? /** @@ -626,6 +634,30 @@ public function track_nodes( $model ) { return $model; } + /** + * Checks if any nodes have been resolved. + * + * This method is used to determine whether any nodes (or models) + * were successfully resolved during the GraphQL query processing. + * It returns the current state of the `nodes_resolved` flag. + * + * @return bool True if any nodes have been resolved, false otherwise. + */ + public static function areNodesResolved() { + return self::$nodes_resolved; + } + + /** + * Resets the nodes resolved status. + * + * This method is called at the beginning of each GraphQL request + * to reset the `nodes_resolved` flag. Ensuring that each request + * starts with a clean state for tracking whether nodes have been resolved. + */ + public static function resetNodesResolved() { + self::$nodes_resolved = false; + } + /** * Returns graphql keys for use in debugging and headers. * diff --git a/wp-graphql.php b/wp-graphql.php index 0304516e00..def82249a2 100644 --- a/wp-graphql.php +++ b/wp-graphql.php @@ -21,6 +21,8 @@ * @version 1.19.0 */ +use WPGraphQL\Utils\QueryAnalyzer; + // Exit if accessed directly. if ( ! defined( 'ABSPATH' ) ) { exit; @@ -182,3 +184,21 @@ function graphql_init_appsero_telemetry() { } graphql_init_appsero_telemetry(); + +add_filter( + 'graphql_process_http_request_response', + static function ( $response, $result, $operation, $request ) { + $nodesResolved = QueryAnalyzer::areNodesResolved(); + + if ( ! $nodesResolved ) { + header( 'Cache-Control: no-cache, must-revalidate' ); + } + + // Correctly reset nodes_resolved for the next request. + QueryAnalyzer::resetNodesResolved(); + + return $response; + }, + 10, + 4 +);