graphql-spec
graphql-spec copied to clipboard
Union types and a default-fragment or wildcard-fragment
I hope I have just missed it, but it seems there is now way to make a graphql client forward compatible so that a server can add a new type to an existing union without breaking the client.
E.g. I imagine a query like:
query {
trafficLight {
__typename
... on Green {
field1
field2
}
... on Red {
field3
field4
}
... on *default {
???
}
}
}
Is something like that already in the Spec or any reason it's not in there and a way to work around it?
Looking at your example, if there are fields that you can query on any arbitrary future type (???) then what you have is actually an interface, not a union.
Unions are forward compatible, clients must be written to support this. Typically this is handled with a switch statement with a default case that either does nothing (return null) or displays a placeholder indicating that the data is not supported/understood; e.g.:
const l = data.trafficLight;
switch (l.__typename) {
case 'Green': return <Green field1={l.field1} />;
case 'Red': return <Red field3={l.field3} />;
default: return <UnknownLightPleaseUpdate typename={l.__typename} />;
}
Also of relevance: https://github.com/graphql/graphql-spec/issues/951
@valentin-panalyt Did the above solve your issue? If so, can we close this issue?
Yes, the issue can be closed. Thank you.