0
votes

There appears to be very little info available on this...I found the article below and it's got me close but it's not working:

How do I create a GraphQL subscription with Apollo Client in Vanilla JS

That post is a little old tho and I'm using apollo client v2.6.8, this is my code:

           const subs = gql`
           subscription onItemAdded 
           {
              itemAdded {
               ItemName
              }
           }`

           var subscriptionObserver = apolloClient.subscribe({
                 query: subs
              })
              .subscribe(
                 data => {
                    console.log('Data', data);
                    //See comment below ********
                 },
                 err => { console.error('Error', err); }
              )                

I see data logged in the console (empty, as expected I guess) immediately after subscribe is called but it never fires again when the actual subscription triggers so what am I missing something here?

[The mutation to add an item and trigger the publish is done elsewhere but this (and my server) are working fine as I've verified the subscription when testing from another client (React) so I'm pretty certain that the problem is with the code above.]

1

1 Answers

0
votes

I found the issue here, a typo in the ApolloClient 'link' meant it was setup only for http, I can confirm that the code above works just fine with the config as below:

const httpLink = createHttpLink({
    uri: "http://zzzzzzzzzzzz"
})

const wsLink = new WebSocketLink({
    uri: "ws://zzzzzzzzzzzzz",
    timeout: 5000,
    options: {
      reconnect: true
    }
});

const link = split(    
    ({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === 'OperationDefinition' &&
        definition.operation === 'subscription'
      );
    },
    wsLink,
    httpLink,
  );

const apolloClient = new ApolloClient({
    link: link,
    cache: new InMemoryCache()
})