GraphQL - 在联合中使用不同类型的相同字段名称 [英] GraphQL - Using same field names in different types within union
问题描述
如果我有这样的联合类型:
If I have a union type like this:
union AllOnboardingQuestionTypes = StepFinal | TimeRangesQuestion | PercentQuestion | SingleSelectQuestion | MultiSelectQuestion | InformationOnly
其中某些类型具有相同的字段名称但类型不同(例如,PercentAnswer
的答案是 float
而 SingleSelect 的答案是 string
),这是进行查询的正确方法吗?
where some of the types have the same field names but different types (e.g. answer for PercentAnswer
is float
whereas SingleSelect's answer is a string
), is this the right way to do the query?
query OnboardingQuestionsQuery {
onboardingQuestions {
... on InformationOnly {
title
description
questionID
inputType
}
... on StepFinal {
title
description
}
... on TimeRangesQuestion {
title
description
timePeriods {
timePeriod
estimatedEnd
estimatedStart
}
}
... on SingleSelectQuestion {
title
description
questionID
inputType
singleSelectAnswer: answer
singleSelectOptions: options {
value
label
}
}
... on MultiSelectQuestion {
title
description
questionID
inputType
multiSelectAnswer: answer
multiSelectOptions: options
}
... on PercentQuestion {
title
description
questionID
inputType
percentAnswer: answer
min
max
}
}
}
别名对我来说似乎很麻烦并且会使事情变得棘手,因为我在改变数据时必须处理我希望我可以只使用 answer
而不是 singleSelectAnswer
.
The aliases seem cumbersome to me and will make things tricky as I'll have to dealias when mutating data
my hope was that I could just use answer
instead of singleSelectAnswer
.
但是当我尝试这样做时,我收到此错误:
But when I try that, I get this error:
{"errors":[{"message":"Fields "answer" conflict because they return conflicting types String! and [Boolean!]!. Use different aliases on the fields to fetch both if this was intentional.","locations":[{"line":64,"column":7},{"line":69,"column":7}]},{"message":"Fields "answer" conflict because they return conflicting types String! and Float!. Use different aliases on the fields to fetch both if this was intentional.","locations":[{"line":64,"column":7},{"line":74,"column":7}]},{"message":"Fields "answer" conflict because they return conflicting types [Boolean!]! and Float!. Use different aliases on the fields to fetch both if this was intentional.","locations":[{"line":69,"column":7},{"line":74,"column":7}]}]}
我是 GraphQL 的新手,不知道这是否是处理它的正确方法.在我的脑海中,我希望遵循多态方法,但也许这不是它完成的方式.
I'm new to GraphQL and don't know if this is the correct way to handle it. In my head I was hoping to follow a polymorphism approach but maybe that's not the way it's done.
推荐答案
我遇到了同样的问题,并找到了三种不同的解决方案:
I had the same problem and find three different solutions to it:
- 使用界面
- 使用联合
- 使用带有附加类型信息的字符串
一切都不是很好,但工作正常.我在 Github 上放了一个包含所有解决方案的简单示例项目:https://github.com/chnoack/apollo-dynamic-types-example
All not very nice but working. I put a simple example project with all solutions on Github: https://github.com/chnoack/apollo-dynamic-types-example
这篇关于GraphQL - 在联合中使用不同类型的相同字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!