首页 > 解决方案 > GraphQL 在类型之前定义联合

问题描述

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

type TypeA {
  fieldA: String
  fieldAorB: TypeAorB
}

type TypeB {
  fieldB: String
}

union TypeAorB = TypeA | TypeB

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

希望这个片段能突出我的困境。

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],
});

标签: graphqlgraphql-js

解决方案


重新阅读文档后:

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

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

IE,

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

推荐阅读