如何在Union中查询具有不同类型的相同字段? [英] How to query same field with different types in an Union?

查看:84
本文介绍了如何在Union中查询具有不同类型的相同字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号

type Duck {
    category: Baz
}

type Foo {
    size: FooSize
}

type Bar {
    size: BarSize
}

union Baz = Foo | Bar

以下查询引发错误 FieldsConflict类型的验证错误:size:它们返回不同的类型FooSize和BarSize @'duck/category'(这是此处所述的预期行为: https://github.com/graphql/graphql-js/issues/53 )

The following query throws an error Validation error of type FieldsConflict: size: they return differing types FooSize and BarSize @ 'duck/category' (it's an intended behaviour as stated here : https://github.com/graphql/graphql-js/issues/53)

{
  duck {
    category {
      ... on Foo {
        size
      }
      ... on Bar {
        size
      }
    }
  }
}

大小为 的别名将使查询正常工作,但是我不能在这里使用它们,因为查询结果将被传递回另一个期望 Duck.category 并具有一个名为 size 的键.

Aliases on size would make the query work, but I can't use them here, because the query results will be passed back to another API which expect Duck.category to have a key named exactly size.

我可以在这里使用任何替代方法或架构重构来使它正常工作吗?

Is there any workaround, or schema refactoring I could use here to get this working ?

推荐答案

总的来说,您只能做三件事来解决该错误:

At a high level, you can only do three things to resolve that error:

  • 重构架构,以使 size 字段是两种类型的相同类型.
  • 别名一个或两个字段.
  • 仅请求字段提供一种类型.
  • Refactor the schema so that the size field is the same type for both types.
  • Alias one or both fields.
  • Only request the field for one of the types.

如果您需要将响应传递给另一个API,最简单的方法是使用别名,然后在将响应发送到API之前转换客户端的响应.

If you need to pass the response to another API, the easiest thing would be to use aliases and then transform the response client-side before sending it to the API.

这篇关于如何在Union中查询具有不同类型的相同字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆