本文介绍了GraphQL 联合和冲突类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目有问题,我在互联网上找不到任何解决方案.这是情况.

I've got an issue on my project and I can't find any solution on the internet. Here is the situation.

  • 我有两种类型的联合(DataResult)(Teaser & Program)
  • 我有一个 Zone 类型和一个 data 字段(一个数组 DataResult)
  • 预告 &Program 具有相同的 title 字段,但类型不同(String vs String!)
  • I've an Union (DataResult) of 2 types (Teaser & Program)
  • I've a Zone type with a data field (an array DataResult)
  • Teaser & Program have the same title field with a different type (String vs String!)

以下是 ZoneTeaserProgram 模式的部分:

Here is parts from Zone, Teaser and Program schemas:

type Program {
    title: String
}

type Teaser {
    title: String!
}

union DataResult = Teaser | Program

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

当我尝试按照以下查询部分所述查询区域数据时,我收到来自 GraphQL 的错误.

When I tried to query zone data as described in the query part below, I've got an error from 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"实体的属性名称相同.我能做什么?

I can't use an alias because the specs needs the same attribute name for all "DataResult" entities. What can I do ?

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

Moreover, even if I set the same Type for title, I've a lot of warning about "missing fields" in the console....

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

PS: I use Vanilla Apollo as GraphQL client (on the server side)

推荐答案

使用接口 为我解决了这个问题,包括缺失字段" - 错误(尽管这意味着这些字段必须与我认为的类型相同).

Using an interface solved this problem for me, including the "missing field" - errors (although this means the fields have to be of the same type I think).

类似的东西

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!]
}

这篇关于GraphQL 联合和冲突类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:44