

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

# 使用 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
}
```

接下来，定义从数据来源中检索 postitem 的 `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`函数的请求处理程序使用的 Dynam AWS AppSync oDB 模块提供的实用程序以`DynamoDBGetItem`作为密钥创建请求。`id` `ddb.get({ key: { id } })`生成相应的`GetItem`操作：

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

AWS AppSync 使用请求从亚马逊 DynamoDB 获取数据。在返回数据后，将由 `GET_ITEM` 函数的响应处理程序进行处理，响应处理程序检查错误，然后返回结果。

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

最后，解析器的响应处理程序直接返回结果。

## 处理错误
<a name="working-with-errors"></a>

如果您的函数在请求期间出现错误，将在函数响应处理程序的 `ctx.error` 中提供该错误。您可以使用 `util.appendError` 实用程序将错误附加到 GraphQL 响应中。您可以使用存储区将错误提供给管道中的其他函数。请参见以下示例：

```
/**
 * 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;
}
```