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

Sar*_*hah 5 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)
    }
  })
});
Run Code Online (Sandbox Code Playgroud)

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

例如我有一个类型

   type Test {
    something: String
    yo: String
    comment: Comment
  }
   type Comment {
    text: String
    createdAt: String
    author: User
  }
Run Code Online (Sandbox Code Playgroud)

在我的解析器中,我想将其拆分,例如这样的

text: {
    something: 'value',
    yo: 'value',
    comment: getComments();
}
Run Code Online (Sandbox Code Playgroud)

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

Jax*_*axx 7

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

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
}
Run Code Online (Sandbox Code Playgroud)

我们还假设您有以下数据库方法:

  • getTest()返回一个带有字段的对象somethingyo并且 commentId
  • getComment(id)返回与字段的对象idtextcreatedAtuserId
  • getUser(id)返回一个带有字段的对象idname并且email

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

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
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 随着您的解析器变得越来越复杂,我鼓励您将任何特定于类型的解析器放在它自己的文件中,然后将所有解析器聚合到一个 `resolvers.js` 文件中。您会发现以这种方式维护您的代码要容易得多。如果您希望我在答案中添加此类目录结构的示例,请告诉我。 (2认同)