Graphql 创建两个 queries.Error 之间的关系在初始化之前无法访问
Graphql create relations between two queries.Error cannot access before initialization
我有这个代码:
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 initialization。
我知道首先我应该声明并且只有在使用之后,但是我在 YouTube 上的一个课程中看到了类似的代码,我认为它应该可以,但它不是。
fields
可以接受一个函数而不是一个对象。这样函数内的代码就不会被立即求值:
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
category: {
type: CategoryType,
resolve: (parent) => Category.findOne({_id: parent.category}),
}
})
我有这个代码:
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 initialization。 我知道首先我应该声明并且只有在使用之后,但是我在 YouTube 上的一个课程中看到了类似的代码,我认为它应该可以,但它不是。
fields
可以接受一个函数而不是一个对象。这样函数内的代码就不会被立即求值:
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
category: {
type: CategoryType,
resolve: (parent) => Category.findOne({_id: parent.category}),
}
})