【问题标题】:GraphQL defining union before typeGraphQL 在类型之前定义联合
【发布时间】:2021-04-01 15:36:28
【问题描述】:

我正在尝试使用 graphql 库定义我的 GraphQL 架构。我试图实现的简化模式是这样的:

type TypeA {
  fieldA: String
  fieldAorB: TypeAorB
}

type TypeB {
  fieldB: String
}

union TypeAorB = TypeA | TypeB

我正在努力弄清楚如何使用 graphql 库来实现这一点,因为我无法在定义其他类型之前定义联合类型。

希望这个 sn-p 能突出我的困境。

import * as graphql from "graphql";

const typeA = new graphql.GraphQLObjectType({
  name: "TypeA",
  fields: { 
    fieldA: { type: graphql.GraphQLString },
    fieldAorB: { type: [???] } // what goes here?
  },
});
const typeB = new graphql.GraphQLObjectType({
  name: "TypeB",
  fields: {
    fieldB: { type: graphql.GraphQLString }
  },
});

const typeAorB = new graphql.GraphQLUnionType({
  name: "TypeAorB",
  types: [typeA, typeB],
});

【问题讨论】:

    标签: graphql graphql-js


    【解决方案1】:

    重读后the documentation

    当两种类型需要相互引用,或者一个类型需要在字段中引用自身时,您可以使用函数表达式(也称为闭包或 thunk)来延迟提供字段。

    fields 可以是一个可以稍后解决的闭包。

    即,

    const typeA = new graphql.GraphQLObjectType({
      name: "TypeA",
      fields: () => ({ // note: closure, not object.
        fieldA: { type: graphql.GraphQLString },
        fieldAorB: { type: typeAorB }
      }),
    });
    

    【讨论】:

      猜你喜欢
      • 2018-09-28
      • 2019-07-01
      • 2017-12-30
      • 2018-03-28
      • 2018-10-22
      • 2021-11-20
      • 2019-06-30
      • 2021-03-17
      相关资源
      最近更新 更多