Search code examples
node.jsgraphqlapollo

How can I subscribe a dynamic topic in graphql?


I have a graphql subscription in nodejs as below:

const resolvers = {
    Query: () => { ... },
    Mutation: () => { ... },
    Subscription: {
        commentAdded: {
          subscribe: withFilter(
            () => pubsub.asyncIterator('COMMENT_ADDED'),
            (payload, variables) => {
             return payload.commentAdded.repository_name === variables.repoFullName;
            },
          ),
        }
    },
};

You can see the topic this subscription uses is COMMENT_ADDED which is a hard coded string. I am wondering whether I can create a dynamic topic name based on user request.

Something like below code. It subscribes the topic with payload.id as its suffix. How can I do this in apollo server?

subscribe: withFilter(
            (payload) => pubsub.asyncIterator('COMMENT_ADDED:'+payload.id),
            (payload, variables) => {
             return payload.commentAdded.repository_name === variables.repoFullName;
            },
          ),

Solution

  • The first function passed to withFilter is the subscribe function, which is what determines the value of the payload. So it cannot be passed the payload as a parameter. The function is passed four parameters, the same as any root resolver -- the root value, the field's arguments, the context and a GraphQLResolveInfo object.