

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

# 使用 Amazon DynamoDB 的範例管道解析程式
<a name="writing-code"></a>

假設您想要在名為 的欄位上連接管道解析程式`getPost(id:ID!)`，該欄位會從具有下列 GraphQL 查詢的 Amazon DynamoDB 資料來源傳回`Post`類型：

```
getPost(id:1){
    id
    title
    content
}
```

首先，`Query.getPost`使用下面的程式碼將簡單的解析程式連接到 。這是簡單解析程式程式碼的範例。請求處理常式中未定義邏輯，回應處理常式只會傳回最後一個函數的結果。

```
/**
 * Invoked **before** the request handler of the first AppSync function in the pipeline.
 * The resolver `request` handler allows to perform some preparation logic
 * before executing the defined functions in your pipeline.
 * @param ctx the context object holds contextual information about the function invocation.
 */
export function request(ctx) {
  return {}
}

/**
 * Invoked **after** the response handler of the last AppSync function in the pipeline.
 * The resolver `response` handler allows to perform some final evaluation logic
 * from the output of the last function to the expected GraphQL field type.
 * @param ctx the context object holds contextual information about the function invocation.
 */
export function response(ctx) {
  return ctx.prev.result
}
```

接著，定義從資料來源擷取後置項目`GET_ITEM`的函數：

```
import { util } from '@aws-appsync/utils'
import * as ddb from '@aws-appsync/utils/dynamodb'

/**
 * Request a single item from the attached DynamoDB table datasource
 * @param ctx the context object holds contextual information about the function invocation.
 */
export function request(ctx) {
	const { id } = ctx.args
	return ddb.get({ key: { id } })
}

/**
 * Returns the result
 * @param ctx the context object holds contextual information about the function invocation.
 */
export function response(ctx) {
	const { error, result } = ctx
	if (error) {
		return util.appendError(error.message, error.type, result)
	}
	return ctx.result
}
```

如果在請求期間發生錯誤，函數的回應處理常式會附加錯誤，並在 GraphQL 回應中傳回呼叫用戶端。將 `GET_ITEM`函數新增至解析程式函數清單。當您執行查詢時，`GET_ITEM`函數的請求處理常式會使用 AWS AppSync DynamoDB 模組提供的 utils，以使用 `id`做為金鑰來建立`DynamoDBGetItem`請求。 `ddb.get({ key: { id } })`會產生適當的`GetItem`操作：

```
{
    "operation" : "GetItem",
    "key" : {
        "id" : { "S" : "1" }
    }
}
```

AWS AppSync 使用 請求從 Amazon DynamoDB 擷取資料。一旦傳回資料，就會由`GET_ITEM`函數的回應處理常式處理，它會檢查錯誤，然後傳回結果。

```
{
  "result" : {
    "id": 1,
    "title": "hello world",
    "content": "<long story>"
  }
}
```

最後，解析程式的回應處理常式會直接傳回結果。

## 使用錯誤
<a name="working-with-errors"></a>

如果在請求期間函數中發生錯誤，則會在 中的函數回應處理常式中提供該錯誤`ctx.error`。您可以使用 `util.appendError`公用程式將錯誤附加至 GraphQL 回應。您可以使用 stash，將錯誤提供給管道中的其他 函數。請參閱以下範例：

```
/**
 * Returns the result
 * @param ctx the context object holds contextual information about the function invocation.
 */
export function response(ctx) {
  const { error, result } = ctx;
  if (error) {
    if (!ctx.stash.errors) ctx.stash.errors = []
    ctx.stash.errors.push(ctx.error)
    return util.appendError(error.message, error.type, result);
  }
  return ctx.result;
}
```