0
0
GraphQLquery~30 mins

Subscription filtering in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Subscription Filtering with GraphQL
📖 Scenario: You are building a chat application where users can subscribe to messages from specific chat rooms.To avoid receiving all messages, you want to filter subscriptions so users only get messages from the rooms they follow.
🎯 Goal: Create a GraphQL subscription that filters messages by roomId so subscribers only receive messages from their chosen chat room.
📋 What You'll Learn
Define a GraphQL type Message with fields id, content, and roomId.
Create a subscription field messageAdded that accepts a roomId argument.
Implement filtering logic in the subscription resolver to only send messages matching the roomId argument.
Use a simple in-memory message list to simulate message publishing.
💡 Why This Matters
🌍 Real World
Filtering subscriptions is essential in real-time apps like chat, notifications, or live updates to avoid sending unnecessary data.
💼 Career
Understanding subscription filtering is important for backend developers working with GraphQL APIs to optimize data flow and user experience.
Progress0 / 4 steps
1
Define the Message type and initial messages
Create a GraphQL type called Message with fields id (ID!), content (String!), and roomId (ID!). Then create a variable called messages as a list with these exact entries: { id: "1", content: "Hello Room 1", roomId: "room1" } and { id: "2", content: "Hello Room 2", roomId: "room2" }.
GraphQL
Hint

Define the Message type with the three fields exactly. Then create a constant messages array with the two message objects.

2
Add the subscription field with roomId argument
Add a subscription field called messageAdded that takes an argument roomId of type ID! and returns a Message.
GraphQL
Hint

Define a Subscription type with a field messageAdded that takes roomId as an argument and returns a Message.

3
Implement subscription resolver with filtering
Create a subscription resolver for messageAdded that filters messages by the roomId argument. Use a function called withFilter that takes a pubsub.asyncIterator('MESSAGE_ADDED') and a filter function comparing payload.messageAdded.roomId with variables.roomId.
GraphQL
Hint

Use withFilter to wrap pubsub.asyncIterator('MESSAGE_ADDED') and filter by comparing payload.messageAdded.roomId with variables.roomId.

4
Publish messages with roomId to trigger filtered subscriptions
Add a function called addMessage that takes id, content, and roomId, pushes the new message to messages, and calls pubsub.publish('MESSAGE_ADDED', { messageAdded: newMessage }).
GraphQL
Hint

Create a function addMessage that adds a new message to messages and publishes it with pubsub.publish.