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

Resolvers

Resolvers are the bulk of the AppSync API implementation and we'll look into the interesting ones in this chapter.

Query.currentUser

Code example

Implementation here.

The first one is to allow users to get themselves, providing an entry point to the object graph:

type Query {
  currentUser: User!
}

This is a useful Query as it allows a convenient entry point that does not depend on any IDs. This is also a rather staightforward one to implement as the database stores the users by their Cognito sub that is accessible under ctx.identity.sub.

The code to fetch the current user from the User table:

import {util} from "@aws-appsync/utils";
export function request(ctx) {
  return {
    version : "2018-05-29",
    operation : "GetItem",
    key: {
      id: {S: ctx.identity.sub}
    }
  };
}
export function response(ctx) {
  if (ctx.error) {
    return util.error(ctx.error.message, ctx.error.type);
  }
  return ctx.result;
}

Query.user

Code example

Implementation here.

The next resolver is similar to the currentUser but allows to get arbitrary users to fetch based on an ID:

type Query {
  user(id: ID!): User
}

This is also a simple one as any user can get any other user, there is no access control on this level. The only difference is that instead of the ctx.identity, it will fetch by ctx.args:

import {util} from "@aws-appsync/utils";
export function request(ctx) {
  return {
    version : "2018-05-29",
    operation : "GetItem",
    key: {
      id: {S: ctx.args.id}
    }
  };
}
export function response(ctx) {
  if (ctx.error) {
    return util.error(ctx.error.message, ctx.error.type);
  }
  return ctx.result;
}

User.posts

Code example

Implementation here.

The next resolver we'll discuss is the User.posts. This allows to get a list of posts made by a particular user:

type User {
  posts(limit: Int, nextToken: String): PaginatedPosts
}

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