Skip to content

GraphQL All-Fields Fragments in Dart: generateAllFieldsFragments

In the last video we turned off autoGenerateQueries for big schemas. This one is about another option in the same config: generateAllFieldsFragments. It generates a fragment with all the fields of each type, and you can use it in the queries you write yourself.

The video shows all of it, and the sections below follow the same order.

Watch on YouTube

Turn it on

In config.json, under the Dart client config, set generateAllFieldsFragments to true and run the generator:

glink -c config.json

Search the generated client for the fragment names and you will find them: GraphLink generates an all-fields fragment for each type. For Author it has all the author's fields. For Book it has the book's fields and is linked to the author's fragment, because a book has an author.

Use them in your own queries

You can use these fragments in your own queries.graphql, even though they are declared nowhere in your code. They exist in GraphLink's memory during generation, so it recognises them. In the video I change getBooksWithoutAuthors to use the all-fields fragment for the author, regenerate, and the method now includes authors. The query that is sent contains the fragment, which is declared in the generated code.

A typo is a generation error

If you misspell the fragment name, GraphLink tells you at generation time that it did not find it, because it is not declared anywhere. You find out when you run glink, not when the app calls the server.

The response class follows the selection

As in the custom queries video, the response class depends on what the query selects. When the query used id, title and the author, the class had those. After switching to the all-fields fragment and regenerating, the class changed with it. I keep the generated file open next to the query in a split view in the video, so you can watch it change.

The shorthand

You can write the fragment with the type in its name, the all-fields fragment of that type. There is also a shorthand where you only write _all_fields, and GraphLink infers the type from where you use it: inside author it is the author's fields, inside books it is the book's fields.

I prefer the shorthand. The second example in the video removes the title field from the selection, uses the shorthand under books, and GraphLink recognises that it is a Book.

Try it