GraphQL circular dependency

半世苍凉 提交于 2019-12-05 10:15:36
piotrbienias

This is rather typical problem of modules circular dependency - you can refer to this question How to deal with cyclic dependencies in Node.js. In this case it has nothing to do with GraphQL.

What is more, you do module.exports = { PostType } however in AuthorType you perform var PostType = require('./post'), shouldn't that be var PostType = require('./post').PostType? I suppose this is the cause of below error you get:

Can only create List of a GraphQLType but got: [object Object].

Because your PostType is now { PostType: ... } and not a GraphQLObjectType instance.

piotrbienias' response led me to the correct thread. I've read it before but didn't understand completely. It is necessary to define the exports before you require the class. In my case, i was able to fix it like this:

module.exports.AuthorType = new graphql.GraphQLObjectType({
  name: "AuthorType",
  fields: () => {
        var PostType = require("./post").PostType;
        return {
            _id: {
                type: graphql.GraphQLID
            },
            name: {
                type: graphql.GraphQLString
            },
            posts: {
                type: new graphql.GraphQLList(PostType),
                description: "Posts written by this author",
                resolve: (author) => PostResolvers.retwArgs(author)
            }
        }
    }
});

and similarly for the PostType. This way, the export is defined before the require is called.

Thanks so much!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!