Graphql 创建两个查询之间的关系。错误无法在初始化之前访问

2024-04-26

我有这个代码:

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();
            }
        }
    }
});

当我尝试编译时,出现 ReferenceError: Cannot access 'CategoryType' before初始化。 我知道首先我应该声明并且只有在使用之后才应该声明,但是我在 YouTube 上的一课中看到了类似的代码,我认为它应该有效,但事实并非如此。


fields可以采用函数而不是对象。这样函数内的代码就不会立即被计算:

fields: () => ({
  id: { type: GraphQLID },
  name: { type: GraphQLString },
  category: {
    type: CategoryType,
    resolve: (parent) => Category.findOne({_id: parent.category}),
  }
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Graphql 创建两个查询之间的关系。错误无法在初始化之前访问 的相关文章

随机推荐