apollographql / graphql-subscriptions

:newspaper: A small module that implements GraphQL subscriptions for Node.js
MIT License
1.59k stars 133 forks source link

pubsub.Publish not working inside async function #189

Closed jomaint closed 5 years ago

jomaint commented 5 years ago

Im using:

pubsub.publish('event', payload) doesn't emit change to subscribed frontend or graphiql.

However, if i add the below code anywhere in the same file: setInterval(() => { pubsub.publish('eventName', { eventName: { id: '123', name: new Date().toString() }, }); }, 2000);

it works. And all subscribed clients will receive the event. A short snippet of my code:

resolver:

...
    Subscription: {
         eventName: {
             subscribe: async (published, args, ctx, info) => await eventResolver(published, args, ctx, info)
    }
...

eventResolver:

export const addedPlaceResolver = (published, args, ctx, info) => {
    console.log("called",published, args);
    return pubsub.asyncIterator('eventName');
}

exact code elsewhere in my other resolver:


...
pubsub.publish('eventName', { eventName: payload });
...

I have event resorted to logging, pubsub.js in graphql-subscriptions/dist and it seems to have received the trigger as well:

pubsub.js

...
PubSub.prototype.publish = function (triggerName, payload) {
    console.log('PUBSUB PUBLISHING', triggerName, payload )
    this.ee.emit(triggerName, payload);
    return Promise.resolve();
};
...

Appreciate any help if I have missed out something

jomaint commented 5 years ago

I managed to get it to work by doing the follow: I was using apollo-server 1.4 then i upgraded it to apollo-server 2.2 and it seems to have fixed it. To anyone who encounters this issue in the future, hope this helps you

sourabhamancha commented 4 years ago

Hey. I'm facing this very same issue. I'm using apollo-server 2.16.1. I followed your method and it didn't work. Any help would be appreciated.

rufaidemir commented 3 years ago

Did you find any solition?

sourabhamancha commented 3 years ago

Yess. I was creating a new instance of pubsub, instead of passing the same pubsub object. I fixed it by passing the pubsub object through calls.

meirankri commented 3 years ago

thks @sourabhamancha its finaly work for me