Standalone Apollo Graphql Websocket Subscriptions

1 minute read

This is just a quick article on how to create a simple standalone Apollo client to test Graphql subscriptions. I needed something like this when we ran into some strange issues at work, where our Graphql backend (Kotlin) and Apollo React frontend stopped working, or got into a refresh loop. To easily test this I wanted something I could script to easily run a couple of scenarios without having to use a browser.

I couldn’t really find a good example, though, how to do this, so after looking through some samples, and libraries, I came up with this:

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import { WebSocketLink } from "apollo-link-ws";
import { SubscriptionClient } from "subscriptions-transport-ws";
import ws from 'ws';

let args = process.argv.slice(2);
if (args.length != 1) {
    console.log(`Expected a single arguments ${process.argv} as query`)
    process.exit(1);
}
let query = args[0];

// the endpoint we're connecting to
const GRAPHQL_ENDPOINT = "wss://some/endpoint/for/subscriptions";

// setup a subscription client for that endpoint
const subscriptionClient = new SubscriptionClient(GRAPHQL_ENDPOINT, {
    reconnect: true
}, ws);

// using the subscription client to set up a websocket link
// which can be passed into the apollo client
const link = new WebSocketLink(subscriptionClient);
let cc = new ApolloClient({
    link: link,
    cache: new InMemoryCache()
});

// The subscription we want to follow, just parse it from the string
const asGql = gql`${query}`

// subscribe
const s = cc.subscribe({
    query: asGql
})

s.subscribe({
    next: ({ data }) => console.log(data)
});

And the following package.json:

{
  "name": "standalone-apollo-client",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "typescript": "^3.8.2"
  },
  "dependencies": {
    "@oitmain/apollo-client-standalone": "^1.0.0",
    "apollo-link-ws": "^1.0.19",
    "subscriptions-transport-ws": "^0.9.16"
  }
}

This small node script takes a graphql subscription as its argument, and by just changing the callback function, you can quickly test your subscriptions. In the end it really helped me determining what was wrong (which in the end wasn’t in the FE or the BE, with an obscure HAProxy configuration).

Updated: