federation icon indicating copy to clipboard operation
federation copied to clipboard

An alternative to reuseFragments

Open samuelAndalon opened this issue 2 years ago • 0 comments

Query Planning algorithm expands all fragments in the main Operation Definition as starting point, then reuseQueryFragments configuration option will attempt to reuse fragments from the original operation with all the complexities and edge use cases that it implies.

What if, instead of relying on the human that wrote the query, which easily could avoid using fragments we attempt to programmatically try to solve this issue?

The idea is to not touch query planning at all (the algorithm is already too complex) and once query planning is done (or when creating a FetchNode), attempt to optimize the resulting operation.

The optimization would consist of:

  1. Traverse the AST.
  2. Search for InlineFragment nodes in SelectionSet nodes.
  3. Create a FragmentDefinition of the SelectionSet of that InlineFragments.
  4. Append that FragmentDefinition to the document AST.
  5. replace the InlineFragment in the SelectionSet with a FragmentSpread.

This optimization is scoped for operations that are heavily relying on polymorphism. It won't need a graphQL schema at all, as everything that is needed is already in the AST.

The graphql-js implementation already provides a DFS visit function that we can use

samuelAndalon avatar Dec 18 '23 17:12 samuelAndalon