3

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 .

CoolOS
  • 91
  • 9

2 Answers2

1

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

benawad
  • 685
  • 7
  • 17
  • Thanks @benawad for the response. I have already that in place , where I am in one of the mutation using ```pubsun.publish``` to the given topic . but when i run the subscription it's not listening ..and returning back null .when i try putting console.log i see ```subscribe``` not executed – CoolOS Jul 17 '20 at 19:41
  • have you found the solution? I thinnk i'm missing something too – Mohsin Amjad Mar 06 '22 at 22:48
0

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.