【问题标题】:GraphQL is there a way to get resolved Union type fields without explicit "...on" query?GraphQL 有没有办法在没有明确的“...on”查询的情况下获得解析的联合类型字段?
【发布时间】:2018-10-27 09:41:18
【问题描述】:

我的架构文件中定义了以下联合:

union ContentUnion = Content | Setting | Page | Picture

例如 Setting

的这种类型定义
type Setting {
    id: String!
    doctype: String!
    name: String!
}

我还有一个适用于 ContentUnion 的类型解析器。

使用这个查询

{ 
 content(id: "113804"){
  ... on Setting{
      id
  }
 }
}

我能够检索一个值。但这对我来说感觉很奇怪,因为我不明白为什么我必须明确指出 Type 是 Setting。我认为这就是 TypeResolver 的实际用途?

我想简单地使用这个查询

  { 
     content(id: "113804"){
      id
    }
  }

但结果是:

{
  "data": null,
  "errors": [
    {
      "message": "Validation error of type FieldUndefined: Field 'id' in type 'ContentUnion' is undefined @ 'content/id'",
      "locations": [
        {
          "line": 1,
          "column": 26
        }
      ],
      "description": "Field 'id' in type 'ContentUnion' is undefined",
      "validationErrorType": "FieldUndefined",
      "queryPath": [
        "content",
        "id"
      ],
      "errorType": "ValidationError",
      "path": null,
      "extensions": null
    }
  ],
  "extensions": null,
  "dataPresent": false
}

这是因为架构无法在 ContentUnion 联合类型上找到 id 字段,因为它是一个联合。我想知道是否有办法让它工作?因为它会在我的实现中为我消除很多头痛。

【问题讨论】:

    标签: java graphql-java


    【解决方案1】:

    如果您创建一个返回联合的查询,则每个联合成员可能具有不同的结构。在 GQL 查询中,您可以定义要返回的类型的哪些属性。

    如果你有一个联合返回类型,你必须为每个联合类型指定想要的属性:

    { 
     content(id: "113804") {
      
      ... on Setting{
          id
      }
    
      ... on Page{
          title
          slug
      }
    
     }
    }
    

    根据内容元素113804 的类型,您将获得四种类型之一,但您事先不知道它会是什么。因此,您必须为每个联合类型提供一个属性选择。

    【讨论】:

      【解决方案2】:

      很抱歉,您必须使用带类型片段的查询。

      根据unions in the GraphQL specification,GraphQL 联合表示一个对象,它可能是 GraphQL 对象类型列表之一,但在这些类型之间不提供保证字段。 没有字段可以在不使用类型片段的情况下在联合上查询。

      【讨论】:

        猜你喜欢
        • 2019-09-28
        • 2016-01-19
        • 2011-07-03
        • 2019-10-16
        • 2018-02-14
        • 1970-01-01
        • 2018-08-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多