GraphQL
Beginner
1 min read
Filtering Subscription Events
Example
import { withFilter } from 'graphql-subscriptions';
const typeDefs = `#graphql
type Message {
id: ID!
channelId: ID!
text: String!
sender: String!
}
type Subscription {
messageAdded(channelId: ID!): Message!
}
`;
const resolvers = {
Subscription: {
messageAdded: {
// withFilter: only deliver if channelId matches
subscribe: withFilter(
() => pubsub.asyncIterator(['MESSAGE_ADDED']),
(payload, variables) => {
return payload.messageAdded.channelId === variables.channelId;
}
),
},
},
};
// Client subscription:
// subscription WatchChannel($channelId: ID!) {
// messageAdded(channelId: $channelId) {
// id
// text
// sender
// }
// }
// Apollo Client setup for subscriptions:
// import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
// import { createClient } from 'graphql-ws';
//
// const wsLink = new GraphQLWsLink(createClient({
// url: 'ws://localhost:4000/graphql',
// }));
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL