在 express GraphQL 中解析嵌套数据

Resolving nested data in express GraphQL

我目前正在尝试解析一个包含配料参考的简单食谱列表。

数据布局如下所示:

type Ingredient {
  name: String!
  amount: Int!
  unit: Unit!
  recipe: Recipe
}

type Recipe {
  id: Int!
  name: String!
  ingredients: [Ingredient]!
  steps: [String]!
  pictureUrl: String!
}

据我了解,我的解析器应该如下所示: 第一个解析食谱,第二个解析食谱中的配料字段。它可以(根据我的理解)使用配方提供的参数。在我的食谱对象中,成分由 id (int) 引用,所以这应该是参数(至少我是这么认为的)。

var root = {
  recipe: (argument) => {
       return recipeList;
  },
  Recipe: {
    ingredients: (obj, args, context) => {
        //resolve ingredients
    }
  },

这些解析器像这样传递给应用程序:

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
  rootValue: root,
}));

但是,我的解析器好像没有被调用。我希望在查询中查询时即时解析成分。

端点有效,但我一查询成分,就返回一条错误消息 "message": "Cannot return null for non-nullable field Ingredient.name.",

当我尝试在我的解析器中记录传入参数时,我发现它从未执行过。不幸的是,我找不到像我一样使用 express-graphql 时如何使用它的示例。

如何在 express-graphQL 中为嵌套类型编写单独的解析器?

只能通过 root 定义查询和变更的解析器,即使这样也是不好的做法。我猜你正在使用 buildSchema 构建你的模式,这通常是一个坏主意,因为 the generated schema will only use default resolvers.

在使用普通 GraphQL.js 时,为 ingredients 等字段定义解析器的唯一方法是不使用 buildSchema。不是从字符串生成模式,而是以编程方式定义它(即定义 GraphQLSchema 及其使用的所有类型)。

执行上述操作非常痛苦,尤其是当您已经在字符串或文档中定义了架构时。因此,另一种选择是使用 graphql-tools' makeExecutableSchema,它可以让您将这些解析器注入到您的类型定义中,就像您尝试做的那样。 makeExecutableSchema returns 一个 GraphQLSchema 对象,因此您可以将它与现有代码一起使用(如果您不想,则不必将中间件更改为 apollo-server)。