首页 文章

多对多的graphql架构错误

提问于
浏览
0

我是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

    问题是 UserType 需要 GroupTypeGroupType 需要 UserType :这称为循环依赖 .

    会发生什么是需要 UserType.js ,在完成运行时导出 {} (这是标准的Node.js模块执行),需要 GroupType ,这需要返回 UserType 并返回一个空对象,并将正确的GraphQL GroupType 导出到 UserType . 所以 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
                ...
            }
        })
    });
    
    ...
    

相关问题