graphql-spec icon indicating copy to clipboard operation
graphql-spec copied to clipboard

Union types and a default-fragment or wildcard-fragment

Open valentin-panalyt opened this issue 3 years ago • 2 comments

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?

valentin-panalyt avatar Jun 01 '22 19:06 valentin-panalyt

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

benjie avatar Jun 02 '22 07:06 benjie

@valentin-panalyt Did the above solve your issue? If so, can we close this issue?

benjie avatar Jun 17 '22 17:06 benjie

Yes, the issue can be closed. Thank you.

valentin-panalyt avatar Sep 01 '22 13:09 valentin-panalyt