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


To add real-time functionality, we need to implement the subscriptions defined in the schema as well. We defined 2 subscriptions clients can use as well as specific events for each of them:

type PostEvent {
  userId: ID!
  post: Post!

type CommentEvent {
  postUserId: ID!
  postDate: AWSDateTime!
  comment: Comment!

type Subscription {
  post(userId: ID!): PostEvent
  @aws_subscribe(mutations: ["notifyPost"])

  comment(postUserId: ID!, postDateStarting: AWSDateTime!):
  @aws_subscribe(mutations: ["notifyComment"])

Let's start with the simpler one: get new posts for a user. The PostEvent has the userId as a top-level field that allows filtering as we've discussed in the Event filtering chapter. And since we only need equality checking, the simpler arguments-based event matching is enough in this case.

Mutation.notifyPost resolver

Code example

Implementation here and here.

The notifyPost mutation that triggers this subscription needs only the Post ID and it fetches everything else:

type Mutation {
  notifyPost(postId: ID!): PostEvent!

This is enough only because a Post can not be deleted in our example. We've covered a case when it is be needed in the removeTodo mutation chapter. While that provides a more robust implementation, the simpler way is enough for this example project.

In the previous chapter we've discussed how to call the notifyPost mutation. Now, let's see the resolver behind it!

The resolver gets the Post by ID and returns the structure defined in the type:

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

Code example

Implementation here.

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