在Express GraphQL中解析嵌套数据

are*_*ser 4 node.js express graphql graphql-js express-graphql

我目前正在尝试解析一个简单的配方列表,其中包含对食材的引用。

数据布局如下所示:

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

type Recipe {
  id: Int!
  name: String!
  ingredients: [Ingredient]!
  steps: [String]!
  pictureUrl: String!
}
Run Code Online (Sandbox Code Playgroud)

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

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

这些解析器通过以下方式传递到应用程序:

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
  rootValue: root,
}));
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Dan*_*den 8

只能通过定义查询和变异的解析器root,即使这样,这也是一种不好的做法。我猜您正在使用构建架构buildSchema,这通常是一个坏主意,因为生成的架构将仅使用默认解析器

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

进行上述操作非常麻烦,特别是如果您已经在字符串或文档中定义了架构的话​​。因此,替代选择是使用graphql-tools的makeExecutableSchema,它使您可以像尝试那样将那些解析器注入到类型定义中。makeExecutableSchema返回一个GraphQLSchema对象,因此您可以将其与现有代码一起使用(如果您不想这样做,则不必将中间件更改为apollo-server)。