In this tutorial, we will explore GraphQL subscriptions and resolvers. The goal is to understand how to fetch real-time data using subscriptions and comprehend the role of resolvers in fetching data.
You will learn:
- The basics of GraphQL subscriptions and resolvers
- Step-by-step guide on how to work with subscriptions and resolvers
- Practical code examples
Prerequisites:
- Basic knowledge of JavaScript
- Familiarity with GraphQL
GraphQL subscriptions are a way to push data from the server to the clients that choose to listen to real-time messages from the server. They are similar to queries and mutations in that they allow you to select the exact data you want to receive.
Resolvers in GraphQL are collection of functions that generate response for a GraphQL query. In simple terms, a resolver acts as a GraphQL query handler. Every resolver function in a GraphQL schema accepts four positional arguments as given below:
- root
: This is the result from the previous / parent type instance.
- args
: This is an object with the arguments passed into the field in the query.
- context
: This is an object shared by all resolvers in a particular query.
- info
: It contains information about the execution state of the query.
// Define a subscription
const SUBSCRIPTION_QUERY = gql`
subscription OnNewItemAdded {
newItemAdded {
id
title
}
}
`;
// Use the subscription in your component
const { data, loading } = useSubscription(SUBSCRIPTION_QUERY);
In this snippet, we define a subscription query OnNewItemAdded
that listens for new items being added. The useSubscription
hook is used in our component to subscribe to this query.
// Define a resolver
const resolvers = {
Query: {
hello: (root, args, context, info) => {
return "Hello, world!";
}
}
};
In this resolver example, we create a resolver for a query hello
. When hello
is queried, it returns the string "Hello, world!".
In this tutorial, we have learned about GraphQL subscriptions and resolvers. We've seen how to set up a subscription to obtain real-time data and how a resolver is used to handle a GraphQL query.
For further learning, you could explore more complex use-cases of subscriptions and how to use arguments in resolvers.
Create a subscription that listens for the removal of an item. The subscription should return the id of the removed item.
Write a resolver for a query goodbye
that returns the string "Goodbye, world!".
Solutions:
// Define a subscription
const SUBSCRIPTION_QUERY = gql`
subscription OnItemRemoved {
itemRemoved {
id
}
}
`;
// Use the subscription in your component
const { data, loading } = useSubscription(SUBSCRIPTION_QUERY);
// Define a resolver
const resolvers = {
Query: {
goodbye: (root, args, context, info) => {
return "Goodbye, world!";
}
}
};
Remember to test your code and ensure everything is working as expected. Further practice could involve using variables in your queries and handling errors in your resolvers.