首页 > 解决方案 > AppSync GraphQL 将 1-1 映射到现有的 GraphQL API

问题描述

我有一个现有的 GraphQL API,它公开了这样的模式:

type AType {
    id: Int!
    name: String!
    children: [BType]
}

type BType {
    id: Int!
    name: String!
}

type Query {
    a(id: ID): A
    as: [A]
}

加上两者中的一些其他省略的标量字段。有几个这样的 API 端点,我想将它们全部聚合在一个 AppSync 实例下,以便前端可以使用单个架构查询一个端点以获取他们需要的所有数据。

我想做的是如果前台发送查询

as {
    id,
    name,
    children {
      id,
      name
    }
}

它会准确地转发到我现有的 GraphQL 端点。AppSync 页面上链接的 AWS 示例讨论了 GraphQL 端点,但唯一链接的代码示例是this,它显示了一个像这样的解析器:

#**
Make an arbitrary HTTP call when this field is listed in a query selection set.
The "relativePath" is the resource path relative to the root URL provided when you
created the HTTP data source. Pass a "params" object to forward headers, body,
and query parameters to the HTTP endpoint.
*#
#if($context.identity.sub == $context.args.userId) 
#set($payload = "query ListOrders {
  listOrders(
    userId: ""$context.args.userId""
    orderDateTimeStatus: {
        le : {
            orderDateTime: ""$context.args.orderDateTime""
        }
    }
    limit: 10
    
  ) {
    items {
      userId
      status
      orderDateTime
      details
      orderId
    }
    nextToken
  }
}")

{
    "version": "2018-05-29",
    "method": "POST",
    "resourcePath": "/graphql",
    "params":{
        "body": {
            "query": "$util.escapeJavaScript($payload)"
        },
        "headers":{
            "Content-Type": "application/json",
            "x-access-token" : "$context.request.headers.x-access-token"

        }
    }
}
#else 
  $utils.unauthorized() 
#end

这仅使用传递给查询的参数,而不是查询结构。如果前端请求 的字段子集A,我只想请求该字段子集,而不是请求所有随后被 AppSync 削减的字段。此外,它甚至不包含嵌套对象——我是否必须每次都获取所有子对象,以便它们稍后被 AppSync 忽略?

假设有 4-5 个微服务有自己的 GraphQL 端点,它们的模式中有不同的查询。我想将请求 1-1 映射到它们。我将如何编写这样的解析器?AppSync 并没有一个很好的操场环境,我可以在其中调试解析器,所以我不能只查看$ctx对象并对原始查询的结构 (AFAIK) 进行逆向工程。

我发现这个问题就是这么问的,但是正如作者所说,那里的解决方案没有按预期工作,而且它似乎已经死了。

标签: amazon-web-servicesgraphqlaws-appsync

解决方案


推荐阅读