How do I make GraphQL subscriptions in NodeJS via Apollo Client?
Asked Answered
C

2

6

I want to make a subscription to a GraphQL server. The application is running in a NodeJS script (i.e. not in the webbrowser).

Here is what I currently do:

const fetch = require("node-fetch").default;
const apollo = require("apollo-boost");
const ApolloClient = apollo.default;
const { gql } = require("apollo-server");

const apolloClient = new ApolloClient({
  uri: "http://localhost:4000/graphql",
  fetch
});

apolloClient.subscribe({
  query: gql`
    subscription {
      startTaskRequested {
        pkRobot
        taskName
      }
    }
  `,
}).subscribe({
  next(x) { console.log(x) },
  error(err) { console.log(`Finished with error: ${ err }`) },
  complete() { console.log('Finished') }
});

The resulting ouput is:

{ data: { startTaskRequested: null } }
Finished

On the GraphQL Server, I can see that the corresponding resolver is never called.

If I make the same subscription query using Apollo's Playground, the subscription works and I get the results that I expect: Apollo Playground

I bumped my head against this for many hours already and I would greatly appreciate it if someone could point me in the right direction.

Cotter answered 11/3, 2020 at 16:18 Comment(0)
C
4

Alright, meanwhile I found a fantastic github repository, which contains the answer to my question: https://github.com/hasura/nodejs-graphql-subscriptions-boilerplate

I'm still not sure why my code above is behaving in this way. If someone is able to explain that, I would appreciate it :-).

Cotter answered 12/3, 2020 at 10:6 Comment(1)
I'm having the same issue.I tried using the recommenced graphql-ws github.com/enisdenjo/graphql-ws , looking at "Client usage in Node", but the socket closes with error 1002. Next I will try using the package from your link although it is marked as 'no longer maintained'Windcheater
S
1

I have used Apollo Client to run a subscription with Appsync - Uses the ApolloHttpLink and ApolloAuthLink packages, hence can be used for any WS based graphql subscriptions - Try this - https://github.com/kodehash/appsync-nodejs-apollo-client/tree/master

Simoniac answered 25/11, 2021 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.