You are viewing the preview version of this book
Click here for the full version.

Resolvers

Resolvers are the glue code between the GraphQL world and the configured data source. For every resolver, two pieces of code are run: the request function that runs before the data source is called and it gets the parameters for the query, and the response function after the data source returns with its result.

The language for resolvers is a constrained version of JavaScript. It supports only the basics, such as arrays, functions, variables, template literals, String operations. But it is missing a lot of more advanced features: there is no support for try..catch, async functions, regular expressions, to name just a few. Also, the functions must be in a single file, and must return in a few milliseconds. In practice, these functions are only capable of doing basic transformations on the data source request and response.

As we've seen in the Data sources chapter, there are several data sources that AppSync supports, each with its parameters and return types. For example, the DynamoDB data source to retrieve an item needs a JSON input with a version, operation, and a key:

export function request(ctx) {
  return {
    version: "2018-05-29",
    operation: "GetItem",
    key: {
      id: {S: "group1"}
    }
  };
}

The function can use a field argument to construct the query with a dynamic id:

export function request(ctx) {
  return {
    version: "2018-05-29",
    operation: "GetItem",
    key: {
      id: {S: ctx.args.id}
    }
  };
}

The context object contains a lot of useful fields that contain information about the request such as the field, the source, the identity of the caller. We'll take a deeper look into what is available in the Context chapter. Also, AppSync provides built-in utility functions for common tasks, such as generating a UUID, converting between date formats, and a few others. We'll see a few examples in the Utils chapter.

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions