GraphQL 字段解析器需要上下文信息

GraphQL field resolver needs contextual information

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

type Book {
  title: String
  author: Author
}

type Author {
  name: String
}

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

getBook returns 对象的解析器形状为:

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

总是返回 authorId

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

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

您可能需要 bookID 作为 parent 在 Author:

中的 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.id

Book.author 附加解析器

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

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

只要 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"
      }
    }
  }
}