0

我是 GrpahQL 的新手,我正在尝试模拟用户和组之间的多对多关系。我的架构中定义了以下类型:

// UserType.js
const {
    GraphQLObjectType,
    GraphQLString,
    GraphQLList,
    GraphQLID } = require('graphql');

const {
    GraphQLEmail } = require('graphql-custom-types');

const GroupType = require('./GroupType'); const AuthService = require('../../services/AuthService');

let authService = new AuthService();

const UserType = new GraphQLObjectType({
    name: "UserType",
    fields: () => ({
        id: { type: GraphQLID },
        user: { type: GraphQLString },
        password: { type: GraphQLString },
        name: { type: GraphQLString },
        lastname: { type: GraphQLString },
        email: { type: GraphQLEmail },
        groups: {
            type: new GraphQLList(GroupType),
            resolve(parentValue) {
                return authService.userGroups(userId);
            }
        }
    }) });


module.exports = UserType;

这是另一个文件:

// GroupType.js
const {
    GraphQLObjectType,
    GraphQLString,
    GraphQLID,
    GraphQLList
} = require('graphql');

const UserType = require('./UserType');
const AuthService = require('../../services/AuthService');

let authService = new AuthService();


const GroupType = new GraphQLObjectType({
    name: "GroupType",
    fields: () => ({
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        description: { type: GraphQLString },
        users: {
            type: new GraphQLList(UserType),
            resolve(parentArgs) {
                return authService.userGroups(parentArgs.id);
            }
        }
    })
});

module.exports = GroupType;

这个例子对我不起作用,因为由于某种原因我得到了这个错误:

错误:只能创建 GraphQLType 的列表,但得到:[object Object]。

此错误仅发生在 GroupType 而不是 UserType 当两者相似时。这里发生了什么?我究竟做错了什么?

4

1 回答 1

0

问题是UserTyperequiresGroupTypeGroupTyperequires UserType:这被称为循环依赖。

发生的事情是UserType.js需要,导出一个{}while 完成运行(这是标准的 Node.js 模块执行), requires GroupType,它需要返回UserType并返回一个空对象,并将正确的 GraphQL 导出GroupTypeUserType. 之所以有效,UserType是因为它是一个列表GroupType,但GroupType它没有一个空对象来满足它对 UserType 的要求。

为了避免这种情况,您可以使用运行时要求GroupType.js

// GroupType.js
...

// Remove the line which requires UserType at the top
// const UserType = require('./UserType');
const AuthService = require('../../services/AuthService');

...

const GroupType = new GraphQLObjectType({
    ...
    fields: () => ({
        ...
        users: {
            type: new GraphQLList(require('./UserType')), // Require UserType at runtime
            ...
        }
    })
});

...
于 2017-11-20T19:04:17.323 回答