【问题标题】:Graphql create relations between two queries.Error cannot access before initializationGraphql创建两个查询之间的关系。初始化前错误无法访问
【发布时间】:2020-05-25 00:30:37
【问题描述】:

我有这个代码:

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 上的一节课中看到了类似的代码,我认为它应该可以工作,但事实并非如此。

【问题讨论】:

    标签: mongodb express mongoose graphql express-graphql


    【解决方案1】:

    fields 可以使用函数而不是对象。这样函数内部的代码就不会立即被评估:

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

    【讨论】:

    • 能否告诉我,上面的代码或使用 buildSchema 或 graphql-tools 哪个更快?
    • @Muhammad 您的架构只会在您首次启动服务器时构建一次。这些不同方法之间的任何速度差异都可以忽略不计,并且不会影响您的服务器能够处理请求的速率。
    • 非常感谢,请告诉我,您是否建议我们使用graphql-tools 作为模式语言?或者我们最好使用像 javascript 函数 fields(), resovle 一样存在于这段代码中??? graphql-tools 是 Facebook 开发的吗?
    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 2021-09-10
    • 2020-10-23
    • 2021-05-17
    相关资源
    最近更新 更多