编辑
添加了我的解决方案作为答案
原始问题
我相信这个问题与循环依赖有关。我昨晚度过了大部分时间,今天尝试了我能在网上找到的所有东西,但似乎没有任何效果。
我试过的:
- 将
fields
prop 转换为返回字段对象的函数 - 将相关字段(在 fields 属性内)转换为返回类型的函数
- 结合上述两种方法
- 最后以 require 语句代替使用引用类型的字段结束(似乎不正确,linter 对此有中风)
这是文件结构:
这是代码:
userType.js
const graphql = require('graphql');
const Connection = require('../../db/connection');
const ConnectionType = require('../connection/connectionType');
const { GraphQLObjectType, GraphQLList, GraphQLString, GraphQLID } = graphql;
const UserType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: { type: GraphQLID },
username: { type: GraphQLString },
email: { type: GraphQLString },
created: {
type: GraphQLList(ConnectionType),
resolve: ({ id }) => Connection.find({ owner: id }),
},
joined: {
type: GraphQLList(ConnectionType),
resolve: ({ id }) => Connection.find({ partner: id }),
},
}),
});
module.exports = UserType;
connectionType.js
const graphql = require('graphql');
const User = require('../../db/user');
const UserType = require('../user/userType');
const { GraphQLObjectType, GraphQLString, GraphQLID, GraphQLInt } = graphql;
const ConnectionType = new GraphQLObjectType({
name: 'Connection',
fields: () => ({
id: { type: GraphQLID },
owner: {
type: UserType,
resolve: ({ owner }) => User.findById(owner),
},
partner: {
type: UserType,
resolve: ({ partner }) => User.findById(partner),
},
title: { type: GraphQLString },
description: { type: GraphQLString },
timestamp: { type: GraphQLString },
lifespan: { type: GraphQLInt },
}),
});
module.exports = ConnectionType;