AppSync:嵌套类型解析器

AppSync: Nested Type Resolver

我尝试包含在以下 graphql 架构中定义的嵌套类型:

type User {
  id: String!
  posts: [Post]
}

type Post {
  id: String!
}

type Query {
  getUser(id: String!): User
  getPost(id: String!): Post
}

如您所见,一个用户有多个 Post。我使用带有 Adjacent List Dynamodb Table(包含用户和 Post 相关行)的 AppSync 作为数据源。在 AppSync 中,我必须使用 请求映射模板 ,但阅读文档后我不明白嵌套类型是如何解析的?

我想在查询 getUser 时应该使用 User_id 调用 Post 解析器。如果是这样,我如何访问 post 解析器中的父 ID?这是 ${context.source} 出现的地方吗?

由于 getPost 查询解析器与 getUser Post 子级调用的 Post 解析器相同,我是否必须将一些逻辑与解析器来处理这两种情况?

一个例子会很有帮助!

您还必须为 User.posts 编写解析器。当您调用 Query.getUser 时,它的解析器将被调用,然后如果您有 User.posts 的解析器,它将使用 ${context.source} 中设置的第一个解析器的上下文调用。

不幸的是,我手头没有一个干净的例子,但如果你使用 CloudFormation,你最终会得到两个解析器,有点像这样:

  UserResolver:
    Type: "AWS::AppSync::Resolver"
    DependsOn: Schema
    Properties:
      ApiId: !Ref YourApiId
      TypeName: Query
      FieldName: getUser
      DataSourceName: !Ref YourDataSource
      RequestMappingTemplate: # you already have this
      ResponseMappingTemplate: ...

  UserPostsResolver:
    Type: "AWS::AppSync::Resolver"
    DependsOn: Schema
    Properties:
      ApiId: !Ref YourApiId
      TypeName: User
      FieldName: posts
      DataSourceName: !Ref YourDataSource
      RequestMappingTemplate: |
        # use context.source.id here to reference the user id
      ResponseMappingTemplate: "$util.toJson($ctx.result.items)"

差不多就是这些了。您走在正确的轨道上,但从字段到解析器的映射需要比您想象的更明确。

这是另一个 Whosebug post,我在其中详细描述了如何执行此操作。标题说的是突变,但它涵盖了突变和查询。 mutation to create relations on AWS AppSync