【问题标题】:GraphQL field resolver needs contextual informationGraphQL 字段解析器需要上下文信息
【发布时间】:2019-02-26 10:30:28
【问题描述】:

也许我的术语不准确。我正在使用 AWS AppSync。我的架构:

type Book {
  title: String
  author: Author
}

type Author {
  name: String
}

type Query {
  getBook(title:String!): Book
}

getBook 的解析器返回一个形状如下的对象:

{
  title: <string>
  authorId: <number>
}

总是返回authorId

我想做的是为字段Book.author 指定一个解析器,它将接收authorId 并从它自己的数据存储中获取该对象。这可能吗?

如果我试图做的事情是不可能的,那么正确的做法是什么,其中一个数据存储是一个包含两列的表 - { title, authorId },而一个单独的存储有一个包含以下列表的表作者,其中主键是列authorId。由于这是两个不同的服务,我不能像 SQL 查询一样加入这两个服务。

【问题讨论】:

  • 解析器函数是代码,基本上一切皆有可能。进行两次调用并重塑数据以满足您计划公开的 API 格式似乎非常合理。

标签: api graphql microservices aws-appsync


【解决方案1】:

只要authorIdgetBook解析器返回,它就可以在解析Book.author时通过$ctx.source.authorId访问。

我使用您的架构通过本地解析器复制了您的 API:

Query.getBook请求映射模板:

{
    "version": "2018-05-29",
    "payload": {
        "title": "$context.arguments.title",
        "authorId": "2" ## returned in addition to other fields. It will be used by Book.author resolver.
    }
}

Query.getBook响应映射模板:

$util.toJson($context.result)

Book.author请求映射模板:

{
    "version": "2018-05-29",
    "payload": {
        "name": "author name with authorId: $context.source.authorId"
    }
}

Book.author响应映射模板:

$util.toJson($context.result)

以下查询:

query {
  getBook(title:"AWS AppSync") {
    title 
    author {
      name
    }
  }
}

将产生结果:

{
  "data": {
    "getBook": {
      "title": "AWS AppSync",
      "author": {
        "name": "author name with authorId: 2"
      }
    }
  }
}

【讨论】:

    【解决方案2】:

    您可能需要在Author 中使用bookID 作为父母的ID:

    type Author {
        # parent's id
        bookID: ID!
        # author id
        id: ID!
        name: String!
    }
    
    type Book {
        id: ID!
        title: String!
        author: Author!
    }
    

    Create Resource时,只需制作:
    - Book.id 作为primary keyBookTable
    - Author.bookID 作为 primary keyAuthor.id 作为 sort key AuthorTable

    您还需要使用$ctx.source.idBook.author附加解析器

    附加Book.author 解析器后,您就可以开始了。您可以得到如下结果:

    getBook(title: "xx") {
      id
      title
      author {
        id
        name
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-16
      • 2020-10-07
      • 2021-07-26
      • 2020-08-26
      • 2019-08-03
      • 1970-01-01
      • 2018-02-18
      • 2020-04-05
      • 2021-07-28
      相关资源
      最近更新 更多