Last active
September 1, 2022 19:26
-
-
Save jasonbahl/ac1846ec8778dbd085adf2ea00bd8392 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UniquePosts { | |
protected $loaded_posts = []; | |
protected $amount_requested = 0; | |
public function __construct() { | |
add_filter( 'graphql_connection_amount_requested', [ $this, 'filter_amount_requested' ], 10, 2 ); | |
add_filter( 'graphql_connection_nodes', [ $this, 'connection_nodes' ], 10, 2 ); | |
} | |
public function filter_amount_requested( $amount_requested, $resolver ) { | |
$this->amount_requested += $amount_requested; | |
return $this->amount_requested; | |
} | |
public function connection_nodes( $nodes, $connection_resolver ) { | |
if ( ! $connection_resolver instanceof \WPGraphQL\Data\Connection\PostObjectConnectionResolver ) { | |
return $nodes; | |
} | |
if ( ! empty( $this->loaded_posts ) ) { | |
$loaded_posts = $this->loaded_posts; | |
$nodes = array_filter( | |
$nodes, | |
static function( $value, $key ) use ( $loaded_posts ) { | |
return ! in_array( $value->databaseId, $loaded_posts, true ); | |
}, | |
ARRAY_FILTER_USE_BOTH | |
); | |
} | |
array_map( function( $node ) { | |
$this->loaded_posts[] = $node->databaseId; | |
}, $nodes ); | |
return $nodes; | |
} | |
} | |
add_action( 'graphql_init', function() { | |
new UniquePosts(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an example of how to ensure multiple queries in the same document contain unique results.
Take this query for example:
Default behavior for WPGraphQL will return the same post for each query:
If we wanted to ensure that multiple queries in the same GraphQL document return unique nodes, we can track the nodes that are loaded, then filter out already loaded nodes from subsequent responses.
Thus, the same query gives us unique results: