AppSync:嵌套类型解析器

Kno*_*dge 11 velocity amazon-dynamodb graphql aws-appsync

我尝试包括在以下graphql模式中定义的嵌套类型:

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

type Post {
  id: String!
}

type Query {
  getUser(id: String!): User
  getPost(id: String!): Post
}
Run Code Online (Sandbox Code Playgroud)

如您所见,一个用户有多个帖子。我将AppSync与相邻列表动态表(包含用户和与Post有关的行)一起用作数据源。在AppSync中,我必须使用请求映射模板,但是在阅读文档后,我还不了解如何解析嵌套类型?

我可以想象在查询getUser后解析器时应使用User_id进行调用。如果是这样,我如何在后解析器中访问父ID?这是${context.source}地方吗?

由于getPost查询解析器与getUser Post子级调用的Post解析器相同,我是否必须将一些逻辑与解析器的请求模板集成在一起以处理两种情况?

一个例子真的很有帮助!

mac*_*tch 10

您还必须为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)"
Run Code Online (Sandbox Code Playgroud)

就是这样。您处在正确的轨道上,但是从字段到解析器的映射需要比您想象的更加明确。

  • 谢谢你。我不可能在文档中找到它(我认为我错过了它,因为没有像这样的嵌套示例),除了对包含父级结果的上下文对象的模糊引用。我现在意识到我错误地假设解析器仅在 Query 或 Mutation 类型中指定,而忽略了它们可以在任何地方指定,这是标准的 graphQL。再次感谢! (2认同)
  • 很高兴它有所帮助,@ FrancisUpton。我发现文档也很难导航,花了我们一段时间才弄清楚该怎么做。 (2认同)