多对多的graphql架构错误

时间:2017-11-20 18:55:43

标签: javascript graphql graphql-js express-graphql

我是GrpahQL的新手,我试图模拟用户和群组之间的多对多关系。我有我的架构中定义的followinf类型:

// 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的List但得到:[object Object]。

此错误仅针对GroupType发生,而不是针对两者类似的UserType。这里发生了什么?我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题在于UserType需要GroupType,而GroupType需要UserType:这称为循环依赖。

会发生什么需要UserType.js,在完成运行时导出{}(这是标准的Node.js模块执行),需要GroupType,这需要返回{{1}然后获取一个空对象,并将正确的GraphQL UserType导出到GroupType。所以UserType有效,因为它是UserType的列表,但GroupType并不是因为需要UserType而得到一个空对象。

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

GroupType.js
相关问题