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

Data sources

In GraphQL, a resolver is a function that gets the arguments and the context for a field and returns a value. This is a generic concept and applies to all GraphQL servers. But how this function is implemented, such as what language it can be written in, can be different between servers.

Field resolving in GraphQL

In AppSync, a resolver is broken into three parts:

  • the request function
  • and the data source
  • the response function

The code contains two function: the request and the response functions. To resolve a field, first the request function converts the GraphQL context into a format suitable for the data source. Then the data source interacts with some external service, such as a database, a Lambda function, or sends an HTTP request. Then the response function gets the result of the data source and converts it into a format suitable for the resolver's result.

Field resolving in AppSync

The resolver code is written in a constrained version of Javascript. It supports most of the basics of the language but is only suitable for short scripts. For example, it must be synchronous and can't use Promises. Moreover, it can't include libraries and its runtime is limited to a few milliseconds.

For example, to get an item from a DynamoDB table, the request function for the groupById resolver can use the id argument:

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

When a query comes for this field, such as this one:

query MyQuery {
  groupById(id: "group1") {

The result object will be:

  version: "2018-05-29",
  operation: "GetItem",
  key: {
    id: {S: "group1"}

The DynamoDB data source knows how to process this input, and fetches an item from the configured table with the id of group1.

Then the response function needs to convert the item to the resolver's result format:

export function response(ctx) {
  if (ctx.error) {
    return util.error(ctx.error.message, ctx.error.type);
  return ctx.result;
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