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

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

问题描述

我有以下型号

type Duck {
    category: Baz
}

type Foo {
    size: FooSize
}

type Bar {
    size: BarSize
}

union Baz = Foo | Bar

以下查询引发错误 FieldsConflict 类型的验证错误:大小:它们返回不同类型的 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
      }
    }
  }
}

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.

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

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