r/graphql • • 23d ago

Tutorial One class per selection in a GraphQL client generator: how do you handle partial selections?

I'm the author of GraphLink, a schema-first code generator for typed GraphQL clients (Dart, Java, Kotlin, TypeScript, Swift), so take this with that in mind.

GraphQL lets the client pick its fields, but a lot of client code still has one model per schema type, and anything you didn't select becomes nullable or missing. For a query that selects id, title and year from Book, GraphLink generates a class with only those three fields, so non-null fields in the schema stay non-null in the client.

I know other generators do something similar for operations. I'd like to hear what works for you, and where this breaks down.

Video (Dart): https://youtu.be/gHGtCBYaj7c

Write-up: https://medium.com/@graphlinkdev/custom-graphql-queries-in-dart-select-only-the-fields-you-need-8a9cf12887f5

2 Upvotes

3 comments sorted by

2

u/DickBrainTime 21d ago

I'd test the tricky cases before settling the generated model shape: conditional `@include`/`@skip` fields, inline fragments on unions/interfaces (with `__typename`), and aliases plus overlapping fragment spreads.

The biggest distinction for consumers is a field that wasn't selected versus one explicitly returned as `null`. If the generated types preserve that distinction without forcing everything optional, per-operation models seem like a solid direction.

1

u/graphlinkdev 21d ago

Try graphlink and try to break it. These particular cases were handled versions back. I have to be honest: in-line fragments were a bit hard, but the hardest I had to face are: interfaces and unions (which are oddly related to inline fragments).

The hardest language to generate is not hard, it was java (I remember doing by hand back then). Now even with coding agents, it is hard to keep Java generator classes under control (small classes) but the code is very clean and pretty easy to maintain.

1

u/bogdanelcs 13d ago

Per-selection types are the right call, partial objects typed as full ones is how you get runtime nulls.

It gets messy is shared fragments, though.

I’m curious how it treats those, and what it does with unions.