GraphQL-在联合体内以不同类型使用相同的字段名称

jez*_*nag 10 graphql

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

union AllOnboardingQuestionTypes = StepFinal | TimeRangesQuestion | PercentQuestion | SingleSelectQuestion | MultiSelectQuestion | InformationOnly
Run Code Online (Sandbox Code Playgroud)

如果某些类型的字段名称相同但类型不同(例如,答案PercentAnswer是is,float而SingleSelect的答案是a string),这是执行查询的正确方法吗?

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
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

别名对我来说似乎很麻烦,会使事情变得棘手,因为在修改数据时我必须处理脱发,我希望我可以用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}]}]}
Run Code Online (Sandbox Code Playgroud)

我是GraphQL的新手,不知道这是处理它的正确方法。在我的脑海里,我希望遵循多态性方法,但也许那不是这样做的方法。

Ste*_*ing 1

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

是的。根据当前(2018 年 6 月)的GraphQL 规范,联合受到这种方式的限制。另请参阅graphql.js上的相应问题

别名看起来很麻烦

避免这种情况的最佳方法是当返回类型不同时,模式指定不同的字段名称。

  • 天哪,规范的一个愚蠢的方面是,如果联合类型可以在存在的字段中变化,为什么不允许字段类型在对象类型之间变化? (8认同)