GraphQL Subscriptions in AWS AppSync

Brijesh Agarwal
3 min readJan 5, 2019

--

Subscriptions are popular feature of GraphQL, as it allows to listen for the updates on the client side; if there are any changes on the backend data.

We have been using AWS AppSync most recently and required to add Subscriptions at few points. AppSync provides short-cuts to integrate subscriptions using annotations.

In GraphQL schema for subscription, just add @aws_subscribe to your subscription and include the mutations for which you want real time data for the mutation event.

input AddEntryInput {
mood: Int!
exercise: ExerciseInput!
}
input EditEntryInput {
id: String!
mood: Int
exercise: ExerciseInput
}
type Mutation {
addEntry(entry: AddEntryInput!): Entry!
editEntry(entry: EditEntryInput!): Entry
deleteEntry(id: String!): Entry
}
type Subscription {
addEntrySubscription(userId: String!): Entry
@aws_subscribe(mutations: ["addEntry"])
}

AWS AppSync subcription return data same that is returned by your mutation query irrespective of what what data you have queried through your subscription query.

Also if you have used filter or condition for your subscription, then subscription only works if that condition data is returned as field by that mutation.

Below are few test cases for add Mutation and subscription.

Subscription to addEntry mutation.

Firstly subscribe to add entry mutation to receive new real time data on any new entry to Entry table for a specific user.

Mutation query to add Entry.

Mutation query to add an entry in Entry table, the returned field for this query does not include userId field in its payload.

Subscribing to addEntry subscription.

Subscription query for subscribing to add entry mutation.

This subscription did not received any result on adding new entry to Entry table as mutation did not return userId field in its payload.

Mutation query to add Entry.

Mutation query to add an entry in Entry table, this time the returned field for this query includes userId field too.

This time subscription did receive an entry which was added via mutation as the mutation query also returned the userId field.

Subscription was only for id, but it received in payload id, mood, userId as mutation query returned all these field.

https://docs.aws.amazon.com/appsync/latest/devguide/real-time-data.html

--

--