Experimenting with GraphQL subscriptions
GraphQL is often praised for being a step forward from data retrieval by making calls to REST APIs from your application’s front-end. Sharing a common schema language puts front-end and middle/back-end developers on the same page. As a front-end developer, you can easily fetch just the data you need with a single call, instead of having to call a bunch of endpoints in series to satisfy your query. Much of the data stitching can now be offloaded to an intermediary graphQL server that will call the underlying data provider services, such as REST APIs, databases and microservices, so you don’t have to.

With the introduction of graphQL subscriptions in 2017, you can now use graphQL schema language to subscribe to to event streams and provide real-time updates to the client. Using the Apollo server package, you can quickly set up a production-ready graphQL server that supports subscriptions over a websocket. Combine this with a regular express server and witness the sensational power of graphQL subscriptions.

Today we’re building a graphQL api for an ice cream shop. Whenever an ice cream is dispensed, we want to be notified. Also, we want to be able to pass a parameter which specifies the ice flavour we want to be notified about.

Getting started

Apollo graphQL’s apollo-server delivers you a production-ready graphQL server without too much hassle. Apollo server can wrap a web server that you already have, like Express.

npm install apollo-server-express express graphql

Include the required packages in your main JS file

const express = require('express');
const { createServer } = require('http'); 
const { ApolloServer, gql } = require('apollo-server-express');

GraphQL schema and resolvers

Let’s start by writing up our types. So far, we need the default required Query type and a basic IceCream type to perform basic graphQL queries. As we’d like to retrieve all ice cream flavours, as well as a single ice cream by flavour, we’ll add the iceCream and iceCreams queries. 

const typeDefs = gql`
    type IceCream {
    id: Int!
    flavour: String!
    description: String!

    type Query {
    iceCream(flavour: String!): IceCream
    iceCreams: [IceCream]

To gather the data that our client request, which is described by the schema, we’ll write resolvers. Resolvers are handler functions for graphQL, which run in response to an incoming request, fetch data from somewhere, and return it to the client in the desired format. Since we don’t have a real back-end to talk to, we’ll have a stub contain our ice cream.

// The excellent flavour descriptions courtesy of https://phrasegenerator.com/wine, with modifications.
const stub = [
    id: 0,
    flavour: 'vanilla',
    description: 'A flippant pepper bouquet and alcoholic garlic essences are blended in'
    id: 1,
    flavour: 'strawberry',
    description: 'Blends indigestible parsnip flavors with a sandy cool ranch flavor'
    id: 2,