GraphQL - 在union中使用不同类型的相同字段名称

时间:2017-05-25 00:47:00

标签: graphql

如果我有这样的联合类型:

union AllOnboardingQuestionTypes = StepFinal | TimeRangesQuestion | PercentQuestion | SingleSelectQuestion | MultiSelectQuestion | InformationOnly

其中一些类型具有相同的字段名但具有不同的类型(例如,PercentAnswer的答案是浮点数,而SingleSelect的答案是字符串),这是执行查询的正确方法吗?

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

但是当我尝试这个时,我得到了这个错误:

{"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的新手,不知道这是否是处理它的正确方法。在我的脑海中,我希望遵循多态方法,但也许这不是它的方式。

2 个答案:

答案 0 :(得分:0)

这是执行查询的正确方法吗?

是的。根据当前(2018年6月)GraphQL specification,以这种方式限制联合。另请参见graphql.js

上的相应问题

别名似乎很麻烦

避免这种情况的最佳方法是让架构在返回类型不同时指定不同的字段名称。

答案 1 :(得分:0)

我遇到了同样的问题,并找到了三种不同的解决方案:

  1. 使用界面
  2. 使用联盟
  3. 使用带有其他类型信息的字符串

虽然不是很好,但是可以正常工作。我将一个带有所有解决方案的简单示例项目放在Github上:https://github.com/chnoack/apollo-dynamic-types-example