Although it takes just a few lines of code to set up your NodeJS code to use GraphQL subscriptions, it does involve going through a few pages of docs. Here's a few lines of boilerplate you can use to get started quickly (copy-paste 🤘).
This is all the code you need
const { execute } = require('apollo-link');
const { WebSocketLink } = require('apollo-link-ws');
const { SubscriptionClient } = require('subscriptions-transport-ws');
const ws = require('ws');
const getWsClient = function(wsurl) {
const client = new SubscriptionClient(
wsurl, {reconnect: true}, ws
);
return client;
};
const createSubscriptionObservable = (wsurl, query, variables) => {
const link = new WebSocketLink(getWsClient(wsurl));
return execute(link, {query: query, variables: variables});
};
const gql = require('graphql-tag');
// A subscription query to get changes for author with parametrised id
// using $id as a query variable
const SUBSCRIBE_QUERY = gql`
subscription liveAuthor($id: Int!) {
author (where: {id: {_eq: $id}}) {
id
name
}
}
`;
const subscriptionClient = createSubscriptionObservable(
'https://test-gql-sub.herokuapp.com/v1alpha1/graphql', // GraphQL endpoint
SUBSCRIBE_QUERY, // Subscription query
{id: 1} // Query variables
);
var consumer = subscriptionClient.subscribe(eventData => {
// Do something on receipt of the event
console.log("Received event: ");
console.log(JSON.stringify(eventData, null, 2));
}, (err) => {
console.log('Err');
console.log(err);
});
This uses the apollo link, subscription-transport-ws libraries.
npm install --save graphql graphql-tag apollo-link apollo-link-ws subscriptions-transport-ws ws
author
with columns id: integer
, name: text
index.js
to https://HEROKU_APP_NAME.herokuoapp.com/v1alpha1/graphql
git clone https://github.com/hasura/nodejs-graphql-subscriptions-boilerplate.git
cd nodejs-graphql-subscriptions-boilerplate
npm i
node index.js