简体   繁体   English

如何在GraphQL中返回带有union查询结果的对象类型?

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

I'm building a GraphQL API. 我正在构建一个GraphQL API。 When returning a union / interface type field, is it possible to have the server tell me the object type? 返回union / interface类型字段时,是否可以让服务器告诉我对象类型? ie 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? 显然,我可以根据需要通过向对象添加“类型”字段来手动添加此功能,但我想这样的内容已经内置到GraphQL中了? Seeing as all of the objects already have names. 看到所有对象都已经有了名字。 Basically I'm trying to access introspection information as part of a normal query. 基本上我试图访问内省信息作为普通查询的一部分。

This is possible using the special meta field __typename , which is available on all Graphql objects and returns the object's Graphql type name. 这可以使用特殊元字段__typename ,它可以在所有Graphql对象上使用,并返回对象的Graphql类型名称。 See http://graphql.org/learn/queries/#meta-fields for more info. 有关详细信息,请参阅http://graphql.org/learn/queries/#meta-fields

PS: it looks like __typename is the only meta field that can be called outside of an introspection query. PS:看起来__typename是唯一可以__typename省查询之外调用的元字段。

Used like: 使用如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM