【问题标题】:Many to Many graphql schema error多对多 graphql 架构错误
【发布时间】:2018-05-04 02:16:00
【问题描述】:

我是 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 当两者相似时。这里发生了什么?我做错了什么?

【问题讨论】:

    标签: javascript graphql graphql-js express-graphql


    【解决方案1】:

    问题是UserType 需要GroupType,而GroupType 需要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
                ...
            }
        })
    });
    
    ...
    

    【讨论】:

    • @user3005919 使用答案旁边的灰色勾号表示您的问题已得到回答;)
    猜你喜欢
    • 2020-11-26
    • 2017-06-12
    • 2018-12-10
    • 2018-10-15
    • 1970-01-01
    • 2014-01-23
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多