This tutorial aims to guide you through the process of defining subscription resolvers in GraphQL. The subscription resolvers are crucial for managing the logic that initiates and terminates subscriptions.
By the end of this tutorial, you will:
Basic knowledge of JavaScript and GraphQL is required to fully benefit from this tutorial.
In GraphQL, a subscription is a type that allows a server to send data to its clients when a specific event happens. Subscription resolvers are functions that contain the logic for setting up and tearing down subscriptions.
There are three kinds of resolver functions in a subscription:
subscribe
: It's a function that returns an AsyncIterator which is used by GraphQL to push the event data.resolve
: This function is optional. It can be used to format the response, similar to the way we use resolvers in a query or mutation.unsubscribe
: This function is rarely used. It's used to clean up things like closing database connections, etc.const resolver = {
Subscription: {
newMessage: {
subscribe: () => pubsub.asyncIterator('NEW_MESSAGE'),
resolve: payload => {
return payload;
},
},
},
};
In this example, newMessage
is a subscription that gets triggered whenever a new message appears. The subscribe
function is using asyncIterator
to listen for 'NEW_MESSAGE' events. The resolve
function is returning the payload directly.
const resolver = {
Subscription: {
newMessage: {
subscribe: withFilter(
() => pubsub.asyncIterator('NEW_MESSAGE'),
(payload, variables) => {
return payload.channelId === variables.channelId;
},
),
resolve: payload => {
return payload;
},
},
},
};
In this example, we've added a filtering function using withFilter
. This function checks if the channelId
in the payload matches the channelId
in the variables.
In this tutorial, we learned about subscription resolvers in GraphQL and how they function to manage the logic that initiates and terminates subscriptions. We also looked at some examples of defining basic and filtered subscription resolvers.
Exercise 1: Define a subscription resolver for a 'newUser' event that gets triggered whenever a new user signs up. Test it with a mock user data.
Exercise 2: Add a filtering function to the 'newUser' subscription resolver that only triggers the subscription if the user's age is above 18.
For more practice, you can try setting up a GraphQL server and implementing these subscription resolvers. You can also try defining resolvers for different kinds of events.