hasura / nodejs-graphql-subscriptions-boilerplate

Boilerplate to setup GraphQL subscriptions in your nodejs code
https://hasura.io
MIT License
80 stars 9 forks source link
boilerplate graphql graphql-subscriptions nodejs

Boilerplate to test GraphQL subscriptions using nodejs

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 🤘).

Usage:

Step 1: Setup the subscription client

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});
};

Step 2: Use it

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);
});

Dependencies:

This uses the apollo link, subscription-transport-ws libraries.

npm install --save graphql graphql-tag apollo-link apollo-link-ws subscriptions-transport-ws ws

Try it out: