Resolvers are the bulk of the AppSync API implementation and we'll look into the interesting ones in this chapter.
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;
}
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;
}
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
}