SyntaxStudy
Sign Up
GraphQL Filtering Subscription Events
GraphQL Beginner 1 min read

Filtering Subscription Events

By default a subscription pushes every event from a PubSub channel to all subscribers. The withFilter higher-order function wraps an asyncIterator and lets you provide a filter function that receives the event payload and the subscription variables, returning true only for events that should be delivered to that subscriber. This is essential for multi-tenant or per-user subscriptions. For example, a chat app should only push messages in the channel the client subscribed to, not messages from every channel.
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',
// }));