Skip to content

Instantly share code, notes, and snippets.

@jasonbahl
Last active September 1, 2022 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonbahl/ac1846ec8778dbd085adf2ea00bd8392 to your computer and use it in GitHub Desktop.
Save jasonbahl/ac1846ec8778dbd085adf2ea00bd8392 to your computer and use it in GitHub Desktop.
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();
});
@jasonbahl
Copy link
Author

This is an example of how to ensure multiple queries in the same document contain unique results.

Take this query for example:

{
  posts( first:1 ) {
    nodes {
       id
       databaseId
       title
    }
  }
  otherPosts:posts(first: 1) {
     nodes {
       id
       databaseId
       title
     }
  }
}

Default behavior for WPGraphQL will return the same post for each query:

CleanShot 2022-08-26 at 13 00 41

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:

CleanShot 2022-08-26 at 13 04 47

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment