GraphQL union and conflicting types

无人久伴 提交于 2019-12-06 18:49:13

问题


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

  • 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!)

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

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

Here is the error:

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

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

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

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


回答1:


It's implemented according to the specification: See 3.a at: http://facebook.github.io/graphql/draft/#SameResponseShape()

See https://github.com/graphql/graphql-js/issues/1361#issuecomment-393489320 for more details.




回答2:


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).

Something along the lines of

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


来源:https://stackoverflow.com/questions/46774474/graphql-union-and-conflicting-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!