【问题标题】:How to add multiple resolvers in a type (Apollo-server)如何在一个类型中添加多个解析器(Apollo-server)
【发布时间】:2019-08-01 03:58:19
【问题描述】:

我用过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();
}

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

【问题讨论】:

    标签: graphql apollo-server


    【解决方案1】:

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

    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() 返回一个对象,其字段为 somethingyocommentId
    • getComment(id) 返回一个包含字段idtextcreatedAtuserId 的对象
    • getUser(id) 返回一个包含字段idnameemail 的对象

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

    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)
      },
    }
    

    希望这会有所帮助。

    【讨论】:

    • 让我试试这个然后回复你
    • 成功了。 :) 但是在文档中找不到它,你有任何文档链接可以很好地解释这一点吗?像这样,我的解析器不会很难管理吗?如果您分享一些技巧,将会很有帮助。因为我是第一次使用 apollo-server。
    • @Sarmad 你可以找到关于阿波罗服务器解析器here的基本文档。将解析器视为根 Query 或 Mutation 中的“冒泡”:如果一个字段没有在父解析器中直接解析,那么它必须由子解析器解析。您还可以使用子解析器在某些条件下覆盖给定字段的值(例如,当用户未通过身份验证时,您可能希望 null 字段)。如果您有任何具体问题,我会很乐意提供帮助。 :)
    • 随着您的解析器变得越来越复杂,我鼓励您将任何特定类型的解析器放在其自己的文件中,然后将所有解析器聚合到一个resolvers.js 文件中。您会发现以这种方式维护您的代码要容易得多。如果您希望我在答案中添加此类目录结构的示例,请告诉我。
    猜你喜欢
    • 2018-10-04
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2021-07-29
    相关资源
    最近更新 更多