本文介绍了AppSync:嵌套类型解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to include nested types defined in the following graphql schema:

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

type Post {
  id: String!
}

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

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

As you can see a User has multiple Posts. I am using AppSync with an Adjacent List Dynamodb Table (which contains both the User and the Post relevant row) as a data source. Within AppSync I have to use a request mapping template, but after reading the documentation I have not understood how nested types are resolved?

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

I would imagine that on querying getUser the Post resolver should be called with the User_id. If so how do I access the parent id within the post resolver? Is this where ${context.source} comes into place?

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

As the getPost query resolver would be the same as the Post resolver, called by the getUser Post child, would I have to integrate some logic with request template of the resolver to deal with both cases?

举个例子真的很有帮助!

An example would be really helpful!

推荐答案

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

You have to also write a resolver for User.posts. When you call Query.getUser it's resolver will be invoked and then if you have a resolver for User.posts it will then be invoked with the context from the first resolver set in ${context.source}.

不幸的是,我手头没有干净的示例,但如果您使用 CloudFormation,您最终会得到两个类似这样的解析器:

I don't have a clean example to hand, unfortunately, but if you're using CloudFormation you'd end up with two resolvers a bit like this:

  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)"

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

That is pretty much it. You were on the right track but the mapping from fields to resolvers needs to be more explicit than you were thinking.

这篇关于AppSync:嵌套类型解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-18 04:13