

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 HTTP 解析程式 in AWS AppSync
<a name="tutorial-http-resolvers-js"></a>

AWS AppSync 可讓您使用支援的資料來源 （即 Amazon DynamoDB AWS Lambda、Amazon OpenSearch Service 或 Amazon Aurora) 來執行各種操作，以及任何任意 HTTP 端點來解析 GraphQL 欄位。在您的 HTTP 端點可供使用之後，您可以使用資料來源連線到這些端點。然後，您可以在結構描述中設定解析程式以執行 GraphQL 操作，例如查詢、變動和訂閱。本教學將逐步說明一些常見的範例。

在本教學課程中，您將 REST API （使用 Amazon API Gateway 和 Lambda 建立） 與 AWS AppSync GraphQL 端點搭配使用。

## 建立 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>

若要在 AWS AppSync 中建立 GraphQL API：

1. 開啟 AWS AppSync 主控台，然後選擇**建立 API**。

1. 選擇 **GraphQL APIs**，然後選擇**從頭開始設計**。選擇**下一步**。

1. 針對 API 名稱，輸入 `UserData`。選擇**下一步**。

1. 選擇 `Create GraphQL resources later`。選擇**下一步**。

1. 檢閱您的輸入，然後選擇**建立 API**。

 AWS AppSync 主控台會使用 API 金鑰身分驗證模式為您建立新的 GraphQL API。您可以使用 主控台進一步設定 GraphQL API 並執行請求。

## 建立 GraphQL 結構描述
<a name="creating-a-graphql-schema"></a>

現在您有一個 GraphQL API，讓我們來建立 GraphQL 結構描述吧。在 AWS AppSync 主控台的**結構描述**編輯器中，使用下列程式碼片段：

```
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 資料來源，請執行以下作業：

1. 在 your AWS AppSync GraphQL API 的**資料來源**頁面中，選擇**建立資料來源**。

1. 輸入資料來源的名稱，例如 `HTTP_Example`。

1. 在**資料來源類型**中，選擇 **HTTP 端點**。

1. 將端點設定為教學課程開始時建立的 API Gateway 端點。如果您導覽至 Lambda 主控台，並在應用程式下尋找您的**應用程式**，您可以找到堆疊產生的端點。在應用程式的設定中，您應該會看到 **API 端點**，其將是您的端點 AWS AppSync。請確定您不包含階段名稱做為端點的一部分。例如，如果您的端點是 `https://aaabbbcccd.execute-api.us-east-1.amazonaws.com/v1`，您會在 中輸入 `https://aaabbbcccd.execute-api.us-east-1.amazonaws.com`。

**注意**  
目前， AWS AppSync 僅支援公有端點。  
如需 AWS AppSync 服務所辨識之認證授權機構的詳細資訊，請參閱 [AWS AppSync HTTPS 端點的 所辨識的憑證授權機構 (CA)](http-cert-authorities.md#aws-appsync-http-certificate-authorities)。

## 設定解析程式
<a name="configuring-resolvers"></a>

在此步驟中，您將將 HTTP 資料來源連線至 `getUser`和 `addUser`查詢。

若要設定`getUser`解析程式：

1. 在 your AWS AppSync GraphQL API 中，選擇**結構描述**索引標籤。

1. 在**結構描述**編輯器右側，在**解析程式**窗格中和**查詢**類型下，尋找 `getUser` 欄位，然後選擇**連接**。

1. 將解析程式類型保留為 ，`Unit`並將執行時間保留為 `APPSYNC_JS`。

1. 在**資料來源名稱**中，選擇您先前建立的 HTTP 端點。

1. 選擇**建立**。

1. 在**解析程式**程式碼編輯器中，新增下列程式碼片段做為您的請求處理常式：

   ```
   import { util } from '@aws-appsync/utils'
   
   export function request(ctx) {
   	return {
   		version: '2018-05-29',
   		method: 'GET',
   		params: {
   			headers: {
   				'Content-Type': 'application/json',
   			},
   		},
   		resourcePath: `/v1/users/${ctx.args.id}`,
   	}
   }
   ```

1. 新增下列程式碼片段做為您的回應處理常式：

   ```
   export function response(ctx) {
   	const { statusCode, body } = ctx.result
   	// if response is 200, return the response
   	if (statusCode === 200) {
   		return JSON.parse(body)
   	}
   	// if response is not 200, append the response to error block.
   	util.appendError(body, statusCode)
   }
   ```

1. 選擇 **Query (查詢)** 標籤，然後執行以下查詢：

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

   這應該會傳回以下回應：

   ```
   {
       "data": {
           "getUser": {
               "id": "1",
               "username": "nadia"
           }
       }
   }
   ```

若要設定`addUser`解析程式：

1. 選擇 **Schema (結構描述)** 標籤。

1. 在**結構描述**編輯器右側，在**解析程式**窗格中和**查詢**類型下，尋找 `addUser` 欄位，然後選擇**連接**。

1. 將解析程式類型保留為 ，`Unit`並將執行時間保留為 `APPSYNC_JS`。

1. 在**資料來源名稱**中，選擇您先前建立的 HTTP 端點。

1. 選擇**建立**。

1. 在**解析程式**程式碼編輯器中，新增下列程式碼片段做為您的請求處理常式：

   ```
   export function request(ctx) {
       return {
           "version": "2018-05-29",
           "method": "POST",
           "resourcePath": "/v1/users",
           "params":{
               "headers":{
                   "Content-Type": "application/json"
               },
           "body": ctx.args.userInput
           }
       }
   }
   ```

1. 新增下列程式碼片段做為您的回應處理常式：

   ```
   export function response(ctx) {
       if(ctx.error) {
           return util.error(ctx.error.message, ctx.error.type)
       }
       if (ctx.result.statusCode == 200) {
           return ctx.result.body
       } else {
           return util.appendError(ctx.result.body, "ctx.result.statusCode")
       }
   }
   ```

1. 選擇 **Query (查詢)** 標籤，然後執行以下查詢：

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

   如果您再次執行`getUser`查詢，應傳回下列回應：

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

## 叫用 AWS 服務
<a name="invoking-aws-services-js"></a>

您可以使用 HTTP 解析程式來設定 AWS 服務的 GraphQL API 介面。對 的 HTTP 請求 AWS 必須使用 [Signature 第 4 版程序](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html)簽署，以便 AWS 可以識別傳送這些請求的人員。當您將 IAM 角色與 HTTP 資料來源建立關聯時， AWS AppSync 會代表您計算簽章。

您提供兩個額外的元件，以使用 HTTP 解析程式叫用 AWS 服務：
+ 具有呼叫 AWS 服務 APIs 許可的 IAM 角色
+ 資料來源中的簽署組態

例如，如果您想要使用 HTTP 解析程式呼叫 [ListGraphqlApis 操作](https://docs.aws.amazon.com/appsync/latest/APIReference/API_ListGraphqlApis.html)，請先[建立 AppSync 擔任並連接下列政策的 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 資料來源 for 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>
```

當您將解析程式連接至結構描述中的 欄位時，請使用下列請求映射範本來 call AWS AppSync：

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

當您對此資料來源執行 GraphQL 查詢時， AWS AppSync 會使用您提供的角色簽署請求，並在請求中包含簽章。查詢會傳回您帳戶中該 AWS 區域的 AWS AppSync GraphQL APIs清單。