Search code examples
graphqlgraphql-ruby

How to return object type with union query results in GraphQL?


I'm building a GraphQL API. When returning a union / interface type field, is it possible to have the server tell me the object type? i.e. something like this

{
  search(text: "an") {
    ... on Human {
      __type
      name
      height
    }
    ... on Droid {
      __type
      name
      primaryFunction
    }
    ... on Starship {
      name
      length
    }
  }
}

// or even better

 {
  search(text: "an") {
    __type // <--- even though it's a Union query, everything has a type right? :/

    ... on Human {
      name
      height
    }
    ... on Droid {
      name
      primaryFunction
    }
    ... on Starship {
      name
      length
    }
  }
}

which would return

{
  "data": {
    "search": [
      {
        "__type": "Human",
        "name": "Han Solo",
        "height": 1.8
      },
      {
        "__type": "Human",
        "name": "Leia Organa",
        "height": 1.5
      },
      {
        "name": "TIE Advanced x1",
        "length": 9.2
      }
    ]
  }
}

Obviously, I could manually add this functionality by adding "type" fields to objects as needed, but I imagine something like this is already built into GraphQL? Seeing as all of the objects already have names. Basically I'm trying to access introspection information as part of a normal query.


Solution

  • This is possible using the special meta field __typename, which is available on all Graphql objects and returns the object's Graphql type name. See http://graphql.org/learn/queries/#meta-fields for more info.

    PS: it looks like __typename is the only meta field that can be called outside of an introspection query.

    Used like:

    {
      search(text: "an") {
        __typename
        ... on Human {
          name
        }
        ... on Droid {
          name
        }
        ... on Starship {
          name
        }
      }
    }