【问题标题】:GraphQL union and conflicting typesGraphQL 联合和冲突类型
【发布时间】:2018-03-28 05:17:05
【问题描述】:

我的项目遇到问题,在互联网上找不到任何解决方案。情况如下。

  • 我有 2 种类型的 Union (DataResult) (Teaser & Program)
  • 我有一个带有data 字段的Zone 类型(一个数组DataResult
  • TeaserProgram 具有相同的 title 字段,但类型不同(StringString!

这是来自ZoneTeaserProgram 架构的部分内容:

type Program {
    title: String
}

type Teaser {
    title: String!
}

union DataResult = Teaser | Program

type Zone {
    (...)
    data: [DataResult!]
}

当我尝试按照下面的查询部分所述查询区域数据时,GraphQL 出现错误。

zones {
    ...zoneFieldsWithoutData
    data {
        ... on Program {
            ...programFields
        }
        ... on Teaser {
            ...teaserFields
        }
    }
}

这是错误:

Error: GraphQL error: Fields \"title\" conflict because they return conflicting types String and String!. Use different aliases on the fields to fetch both if this was intentional

我不能使用别名,因为规范需要所有“DataResult”实体的相同属性名称。我能做什么?

此外,即使我为title 设置了相同的类型,我也有很多关于控制台中“缺少字段”的警告......

PS:我使用 Vanilla Apollo 作为 GraphQL 客户端(在服务器端)

【问题讨论】:

标签: javascript graphql apollo


【解决方案1】:

我知道您不能使用别名,但对于其他可以使用别名的人(包括我):

github 得到的简单答案是使用字段别名:

zones {
    ... on Program {
        programTitle: title
    }
    ... on Teaser {
        teaserTitle: title
    }
}

【讨论】:

  • "我不能使用别名,因为规范要求所有“DataResult”实体具有相同的属性名称。"
【解决方案2】:

使用interface 为我解决了这个问题,包括“缺少字段” - 错误(尽管这意味着字段必须是我认为的相同类型)。

类似的东西

interface DataResult {
    title: String!
}

type Program implements DataResult {
    // Not sure if this can be empty?
}

type Teaser implements DataResult {
    // Not sure if this can be empty?
}

type Zone {
    (...)
    data: [DataResult!]
}

【讨论】:

    【解决方案3】:
    猜你喜欢
    • 2019-11-07
    • 2017-12-30
    • 2018-09-28
    • 2019-07-01
    • 1970-01-01
    • 2016-08-29
    • 2018-06-08
    • 1970-01-01
    相关资源
    最近更新 更多