CoolOS
CoolOS

Reputation: 101

Apollo Server Subscription subscribe method is never called

I have an existing Express ApolloServer . I added subscription to that . I can see when I fire the subscription from Playground, the resolve method is called . But, the subscribe method is never called


const { PubSub, withFilter } = require ('apollo-server');
const pubsub = new PubSub();
const SOMETHING_CHANGED_TOPIC = 'something_changed';

const mySubscription = {

  Subscription: {
    somethingChanged: {
      resolve: root => {
        console.log('subscription server resolve', { root })
        return root
      },
      subscribe: () => {
        console.log('I AM HERE IN SUBSCRIPTION', pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC))
        return pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC)
      }
    }
  }
};

module.exports = { mySubscription}

I can see the console.log('subscription server resolve', { root }) getting printed although root is undefined. But the similar console.log('````') in subscribe is not executed .

Upvotes: 3

Views: 1468

Answers (2)

Emerson Boyd
Emerson Boyd

Reputation: 23

I had a similar issue, there were a couple things I needed to achieve to accomplish this.

  1. I had to remove my resolve() function to get it working. For some reason, having the resolve() function defined caused my subscription not to work.
  2. I also had failed to follow the https://www.apollographql.com/docs/react/data/subscriptions/#setting-up-the-transport. I was trying to request my subscription over the http link instead of over a ws link.

In general, a good test to see where the issue lies is to try to subscribe to your message using the GraphQL sandbox at http://localhost:4000/graphql (or wherever your sandbox is setup to run at when you start your server). If the sandbox subscribes successfully, the issue lies in your client code. If the sandbox fails to subscribe, the issue lies in your server code.

Please let me know if you are still having the issue and I will try to help.

Upvotes: 0

benawad
benawad

Reputation: 705

You need to call pubsub.publish somewhere (usually in one of your resolvers) to trigger the subscription.

https://www.apollographql.com/docs/apollo-server/data/subscriptions/#subscriptions-example

Upvotes: 1

Related Questions