graphql - 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],
});
解决方案
重新阅读文档后:
当两种类型需要相互引用,或者一个类型需要在字段中引用自身时,您可以使用函数表达式(也称为闭包或 thunk)来延迟提供字段。
fields
可以是一个可以稍后解决的闭包。
IE,
const typeA = new graphql.GraphQLObjectType({
name: "TypeA",
fields: () => ({ // note: closure, not object.
fieldA: { type: graphql.GraphQLString },
fieldAorB: { type: typeAorB }
}),
});
推荐阅读
- ios - 如何将新项目添加到当前正在播放旧项目的 AVQueuePlayer
- dexguard - Dexguard 实施
- ios - 如何在 plist 权限中放置问号和感叹号
- python-3.x - kaggle_data在哪里?我找不到这样的库
- c - 在不使用函数指针的情况下在 C 中引用虚拟表的替代方法。
- reactjs - 如何编写 Electron react app starter kit?
- amazon-web-services - 设置 SNS 主题以在一条消息之后触发 Lambda 函数
- excel - Excel 公式使用 more if
- python - 如何更改 NumPy 逻辑函数的基数?
- javascript - 如何在无状态组件中单击按钮时获取输入值?