Graphql创建两个查询之间的关系.初始化前无法访问错误 [英] Graphql create relations between two queries.Error cannot access before initialization
本文介绍了Graphql创建两个查询之间的关系.初始化前无法访问错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码:
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:初始化之前无法访问'CategoryType'.我了解我首先应该声明,并且只有在使用之后才声明,但是我在YouTube的一堂课上看到了类似的代码,我认为它应该可以,但是不能.
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.
推荐答案
字段
可以采用函数而不是对象.这样,函数内部的代码将不会立即被评估:
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}),
}
})
这篇关于Graphql创建两个查询之间的关系.初始化前无法访问错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文