apollographql / graphql-subscriptions

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

Trouble subscribing to the publisher using async iterator #87

Closed EwanValentine closed 7 years ago

EwanValentine commented 7 years ago

I have a graphql server and I'm attempting to trigger an event whenever the status of an entity is updated. I have a mutation for updating the entity, which uses graphql-subscriptions to publish the update for the subscriber to listen to. However, pubsub.subscribe(EVENT_NAME) picked up the change, but when I integrate that into the subscription resolver, it doesn't trigger the update.

I've redacted parts of the code not relevant to the issue for brevity.

My resolver:

Mutation: {
  updateStatus(_, { id, status, hash }) {
    return repository.updateStatus(id, status, hash);
  }
},
Subscription: {
  updatedStatus: {
    subscribe: () => pubsub.asyncIterator('updatedStatus'),
  }
},

My repository:

export const updateStatus = async function(id: String, status: String, hash: String) {
  try {
    const res = await fetch(`${baseURL}/article/${id}/status?publish_hash=${hash}`, {
      headers,
      method: 'PATCH',
      body: JSON.stringify({ status })
    });

    const article = await fetchSingleArticle(id, 'XML', headers.channel, false);

    await pubsub.publish('updatedStatus', article);
    return article;
  } catch (e) {
    console.log(e.message);
  }
}

My schema:

type Mutation {
  updateStatus(id: ID!, status: PublishingStatus = PUBLISHING, hash: String): Article
}

type Subscription {
  updatedStatus(id: ID!): Article
}

schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}

To test this, I'm just using graphiql, which is picking up the websocket connection fine.

I've attempted the publish using both article (as shown) and { updatedStatus: article }, neither seem to get picked up.

As mentioned previously pubsub.subscribe('updatedStatus') does pick up the change. So the issue seems to be related to the Subscription resolver.

I'm going off the following docs: http://dev.apollodata.com/tools/graphql-subscriptions/setup.html#setup

EwanValentine commented 7 years ago

I was using an out of date version of the graphql package. My bad!

Karem1986 commented 3 years ago

Hi Ewen, so your code was all correct? I am learning subscriptions and have an error for cannot connect to WEbsocket but i dont know what can be the problem? Could u please perhaps guide me?