Graphql create relations between two queries.Error cannot access before initialization

孤者浪人 提交于 2020-07-10 10:37:33

问题


I have this code:

const ProductType = new GraphQLObjectType({
    name: 'Product',
    fields: {
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        category: {
            type: CategoryType,
            resolve: async (parent) => {
                return await Category.findOne({_id: parent.category});
            }
        }
    }
});

const CategoryType = new GraphQLObjectType({
    name: 'Category',
    fields: {
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        products: {
            type: ProductType,
            resolve: async (parent, args) => {
                return await Product.find({category: parent._id});
            }
        }
    }
});

const Query = new GraphQLObjectType({
    name: 'Query',
    fields: {
        Categories: {
            type: new GraphQLList(CategoryType),
            resolve: async () => {
                return await Category.find();
            }
        }
    }
});

When i try to compile i get ReferenceError: Cannot access 'CategoryType' before initialization. I understand that first of all I should declare and only after that use, but I saw a similar code in one lesson on YouTube, and I think that it should work, but it’s not.


回答1:


fields can take a function instead of an object. This way the code inside the function won't be evaluated immediately:

fields: () => ({
  id: { type: GraphQLID },
  name: { type: GraphQLString },
  category: {
    type: CategoryType,
    resolve: (parent) => Category.findOne({_id: parent.category}),
  }
})


来源:https://stackoverflow.com/questions/60137692/graphql-create-relations-between-two-queries-error-cannot-access-before-initiali

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