

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 在中使用 HTTP 解析器 AWS AppSync
<a name="tutorial-http-resolvers"></a>

**注意**  
我们现在主要支持 APPSYNC\$1JS 运行时系统及其文档。请考虑使用 APPSYNC\$1JS 运行时系统和[此处](https://docs.aws.amazon.com/appsync/latest/devguide/tutorials-js.html)的指南。

AWS AppSync 允许您使用支持的数据源（即亚马逊 DynamoDB AWS Lambda、 OpenSearch 亚马逊服务或 Amazon Aurora）执行各种操作，此外还可以使用任何任意 HTTP 终端节点来解析 GraphQL 字段。在您的 HTTP 终端节点可用后，您可以使用数据来源连接它们。然后，您可以在架构中配置一个解析器以执行 GraphQL 操作（如查询、变更和订阅）。本教程将引导您了解一些常见示例。

在本教程中，您将使用 REST API（使用 Amazon API Gateway 和 Lambda 创建）和 GraphQL AWS AppSync 终端节点。

## 一键设置
<a name="one-click-setup"></a>

如果您想在 AWS AppSync 配置了 HTTP 终端节点的情况下自动设置 GraphQL 终端节点（使用 Amazon API Gateway 和 Lambda），则可以使用以下模板： AWS CloudFormation 

[https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/http/http-full.yaml](https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/http/http-full.yaml)

## 创建 REST API
<a name="creating-a-rest-api"></a>

您可以使用以下 AWS CloudFormation 模板来设置适用于本教程的 REST 端点：

[https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/http/http-api-gw.yaml](https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/http/http-api-gw.yaml)

 AWS CloudFormation 堆栈执行以下步骤：

1. 设置 Lambda 函数，其中包含您的微服务的业务逻辑。

1. 使用以下endpoint/method/content类型组合设置 API Gateway REST API：


****  

| API 资源路径 | HTTP 方法 | 支持的内容类型 | 
| --- | --- | --- | 
|  /v1/users  |  POST  |  application/json  | 
|  /v1/users  |  GET  |  application/json  | 
|  /v1/users/1  |  GET  |  application/json  | 
|  /v1/users/1  |  PUT  |  application/json  | 
|  /v1/users/1  |  DELETE  |  application/json  | 

## 创建您的 GraphQL API
<a name="creating-your-graphql-api"></a>

要在以下位置创建 GraphQL API，请执行以下操作： AWS AppSync
+ 打开 AWS AppSync 控制台并选择**创建 API**。
+ 对于 API 名称，请键入 `UserData`。
+ 选择**自定义架构**。
+ 选择**创建**。

 AWS AppSync 控制台使用 API 密钥身份验证模式为您创建一个新的 GraphQL API。您可以根据本教程后面的说明，使用控制台设置 GraphQL API 的其余部分，并针对它运行查询。

## 创建 GraphQL 架构
<a name="creating-a-graphql-schema"></a>

现在，您有一个 GraphQL API，让我们创建一个 GraphQL 架构。在 AWS AppSync 控制台的架构编辑器中，确保架构与以下架构相匹配：

```
schema {
    query: Query
    mutation: Mutation
}

type Mutation {
    addUser(userInput: UserInput!): User
    deleteUser(id: ID!): User
}

type Query {
    getUser(id: ID): User
    listUser: [User!]!
}

type User {
    id: ID!
    username: String!
    firstname: String
    lastname: String
    phone: String
    email: String
}

input UserInput {
    id: ID!
    username: String!
    firstname: String
    lastname: String
    phone: String
    email: String
}
```

## 配置您的 HTTP 数据来源
<a name="configure-your-http-data-source"></a>

要配置 HTTP 数据来源，请执行以下操作：
+ 在**DataSources**选项卡上，选择 “**新建**”，然后键入数据源的友好名称（例如`HTTP`）。
+ 在 **Data source type (数据来源类型)** 中，选择 **HTTP**。
+ 将终端节点设置为创建的 API 网关终端节点。确保不将阶段名称作为终端节点的一部分包含在内。

 **注意：**目前 AWS AppSync 仅支持公共终端节点。

 **注意：**有关该 AWS AppSync 服务识别的认证机构的更多信息，请参阅 [HTTPS 端点的证书颁发机构 (CA) 认可 AWS AppSync](http-cert-authorities.md#aws-appsync-http-certificate-authorities)。

## 配置解析器
<a name="configuring-resolvers"></a>

在此步骤中，您将 HTTP 数据来源连接到 **getUser** 查询。

设置解析器：
+ 选择**架构**选项卡。
+ 在右侧的**数据类型**窗格中，在 **Query** 类型下面找到 **getUser** 字段，然后选择**附加**。
+ 在 **Data source name (数据来源名称)** 中，选择 **HTTP**。
+ 在 **Configure the request mapping template (配置请求映射模板)** 中，粘贴以下代码：

```
{
    "version": "2018-05-29",
    "method": "GET",
    "params": {
        "headers": {
            "Content-Type": "application/json"
        }
    },
    "resourcePath": $util.toJson("/v1/users/${ctx.args.id}")
}
```
+ 在 **Configure the response mapping template (配置响应映射模板)** 中，粘贴以下代码：

```
## return the body
#if($ctx.result.statusCode == 200)
    ##if response is 200
    $ctx.result.body
#else
    ##if response is not 200, append the response to error block.
    $utils.appendError($ctx.result.body, "$ctx.result.statusCode")
#end
```
+ 选择 **Query (查询)** 选项卡，然后运行以下查询：

```
query GetUser{
    getUser(id:1){
        id
        username
    }
}
```

此查询应返回以下响应：

```
{
    "data": {
        "getUser": {
            "id": "1",
            "username": "nadia"
        }
    }
}
```
+ 选择**架构**选项卡。
+ 在右侧的**数据类型**窗格中，在 **Mutation** 下面找到 **addUser** 字段，然后选择**附加**。
+ 在 **Data source name (数据来源名称)** 中，选择 **HTTP**。
+ 在 **Configure the request mapping template (配置请求映射模板)** 中，粘贴以下代码：

```
{
    "version": "2018-05-29",
    "method": "POST",
    "resourcePath": "/v1/users",
    "params":{
      "headers":{
        "Content-Type": "application/json",
      },
      "body": $util.toJson($ctx.args.userInput)
    }
}
```
+ 在 **Configure the response mapping template (配置响应映射模板)** 中，粘贴以下代码：

```
## Raise a GraphQL field error in case of a datasource invocation error
#if($ctx.error)
    $util.error($ctx.error.message, $ctx.error.type)
#end
## if the response status code is not 200, then return an error. Else return the body **
#if($ctx.result.statusCode == 200)
    ## If response is 200, return the body.
    $ctx.result.body
#else
    ## If response is not 200, append the response to error block.
    $utils.appendError($ctx.result.body, "$ctx.result.statusCode")
#end
```
+ 选择 **Query (查询)** 选项卡，然后运行以下查询：

```
mutation addUser{
    addUser(userInput:{
        id:"2",
        username:"shaggy"
    }){
        id
        username
    }
}
```

此查询应返回以下响应：

```
{
    "data": {
        "getUser": {
        "id": "2",
        "username": "shaggy"
        }
    }
}
```

## 调用服务 AWS
<a name="invoking-aws-services"></a>

您可以使用 HTTP 解析器为服务设置 GraphQL API 接口 AWS 。对的 HTTP 请求 AWS 必须使用[签名版本 4 流程](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html)进行签名，这样 AWS 才能识别谁发送了这些请求。 AWS AppSync 当您将 IAM 角色与 HTTP 数据源关联时，代表您计算签名。

您还提供了两个额外的组件，用于通过 HTTP 解析器调用 AWS 服务：
+ 有权调用 AWS 服务的 IAM 角色 APIs
+ 数据来源中的签名配置

例如，如果您想使用 HTTP 解析器调用该[ListGraphqlApis 操作](https://docs.aws.amazon.com/appsync/latest/APIReference/API_ListGraphqlApis.html)，请先[创建一个附加以下策略的 IAM 角色](attaching-a-data-source.md#aws-appsync-getting-started-build-a-schema-from-scratch)： AWS AppSync 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "appsync:ListGraphqlApis"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
```

------

接下来，为创建 HTTP 数据源 AWS AppSync。在本示例中，您在美国西部（俄勒冈）区域调用 AWS AppSync 。在名为 `http.json` 文件中设置以下 HTTP 配置，其中包括签名区域和服务名称：

```
{
    "endpoint": "https://appsync.us-west-2.amazonaws.com/",
    "authorizationConfig": {
        "authorizationType": "AWS_IAM",
        "awsIamConfig": {
            "signingRegion": "us-west-2",
            "signingServiceName": "appsync"
        }
    }
}
```

然后，使用创建具有关联角色的数据源，如下所示： AWS CLI 

```
aws appsync create-data-source --api-id <API-ID> \
                               --name AWSAppSync \
                               --type HTTP \
                               --http-config file:///http.json \
                               --service-role-arn <ROLE-ARN>
```

当您将解析器附加到架构中的字段时，请使用以下请求映射模板进行调用 AWS AppSync：

```
{
    "version": "2018-05-29",
    "method": "GET",
    "resourcePath": "/v1/apis"
}
```

当您对该数据源运行 GraphQL 查询时，使用您提供的角色对请求进行 AWS AppSync 签名，并在请求中包含签名。该查询会返回您在该区域的账户 APIs 中的 AWS AppSync GraphQL 列表。 AWS 