

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# Exemplo de resolvedor de pipeline com o Amazon DynamoDB
<a name="writing-code"></a>

Digamos que você queira anexar um resolvedor de pipeline em um campo chamado `getPost(id:ID!)` que retorna o tipo `Post` de uma fonte de dados do Amazon DynamoDB com a seguinte consulta do GraphQL:

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

Primeiro, anexe um resolvedor simples a `Query.getPost` com o código abaixo. Este é um exemplo de código de resolvedor simples. Não há lógica definida no manipulador de solicitação, e o manipulador de resposta simplesmente retorna o resultado da última função.

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

Em seguida, defina a função `GET_ITEM` que recupera um postItem da sua fonte de dados:

```
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
}
```

Se houver um erro durante a solicitação, o manipulador de resposta da função anexará no final um erro que será retornado ao cliente chamador na resposta do GraphQL. Adicione a função `GET_ITEM` à sua lista de funções do resolvedor. Quando você executa a consulta, o manipulador de solicitações da `GET_ITEM` função usa os utilitários fornecidos pelo módulo AWS AppSync DynamoDB para criar uma `DynamoDBGetItem` solicitação usando o como chave. `id` `ddb.get({ key: { id } })`gera a `GetItem` operação apropriada:

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

AWS AppSync usa a solicitação para buscar os dados do Amazon DynamoDB. Depois que os dados são retornados, eles são tratados pelo manipulador de resposta da função `GET_ITEM`, que verifica erros e retorna o resultado. 

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

Finalmente, o manipulador de resposta do resolvedor retorna o resultado diretamente.

## Como trabalhar com eventos
<a name="working-with-errors"></a>

Se ocorrer um erro na sua função durante uma solicitação, ele será disponibilizado no manipulador de resposta da função em `ctx.error`. Você pode acrescentar o erro no final da sua resposta do GraphQL usando o utilitário `util.appendError`. É possível disponibilizar o erro para outras funções no pipeline usando o stash. Veja o exemplo abaixo:

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