graphql - 如何在一个类型中添加多个解析器(Apollo-server)

标签 graphql apollo-server

我用过 express-graphql在那里我曾经做过这样的事情。

const SubCategoryType = new ObjectType({
  name: 'SubCategory',
  fields: () => ({
    id: { type: IDType },
    name: { type: StringType },
    category: {
      type: CategoryType,
      resolve: parentValue => getCategoryBySubCategory(parentValue.id)
    },
    products: {
      type: List(ProductType),
      resolve: parentValue => getProductsBySubCategory(parentValue.id)
    }
  })
});

这里我有多个解析器,id and name直接从结果中获取。并且类别和产品有自己的数据库操作。等等。
现在我正在处理 apollo-server我找不到复制这个的方法。

例如我有一个类型
   type Test {
    something: String
    yo: String
    comment: Comment
  }
   type Comment {
    text: String
    createdAt: String
    author: User
  }

在我的解析器中,我想将其拆分,例如这样的
text: {
    something: 'value',
    yo: 'value',
    comment: getComments();
}

注意:这只是我需要的代表。

最佳答案

您可以添加特定于类型的解析器来处理特定字段。假设您有以下架构(基于您的示例):

type Query {
  getTest: Test
}
type Test {
  id: Int!
  something: String
  yo: String
  comment: Comment
}
type Comment {
  id: Int!
  text: String
  createdAt: String
  author: User
}
type User {
  id: Int!
  name: String
  email: String
}

我们还假设您有以下数据库方法:
  • getTest()返回一个带有字段的对象 something , yocommentId
  • getComment(id)返回一个带有字段的对象 id , text , createdAtuserId
  • getUser(id)返回一个带有字段的对象 id , nameemail

  • 您的解析器将类似于以下内容:

    const resolver = {
      // root Query resolver
      Query: {
        getTest: (root, args, ctx, info) => getTest()
      },
      // Test resolver
      Test: {
        // resolves field 'comment' on Test
        // the 'parent' arg contains the result from the parent resolver (here, getTest on root)
        comment: (parent, args, ctx, info) => getComment(parent.commentId)
      },
      // Comment resolver
      Comment: {
        // resolves field 'author' on Comment
        // the 'parent' arg contains the result from the parent resolver (here, comment on Test)
        author: (parent, args, ctx, info) => getUser(parent.userId)
      },
    }
    

    希望这可以帮助。

    关于graphql - 如何在一个类型中添加多个解析器(Apollo-server),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55091665/

    相关文章:

    用于文件下载的 GraphQL 端点

    javascript - 使用 Sequelize 在 GraphQL 查询中将日期时间字段输出为字符串

    node.js - 继承已实现类型 graphql 中的接口(interface)字段

    javascript - GraphQL 数组/列表变量?

    javascript - 使用 Apollo Graphql Server 解析关系文档

    javascript - 如何使用 gatsby-image 在不裁剪的情况下显示图像?

    graphql - 使用中继现代 graphql 添加突变

    go - 如何使用 graphql-go 发出请求

    node.js - 如何使用 Apollo Server 2.0 beta 读取 auth header

    node.js - 错误 : "user" defined in resolvers, 但不在架构中