Create a realtime graph using Nest.js

  • Christian Nwamba
May 4th, 2018
You should already have Node and npm installed on your machine. A basic understanding of Node and TypeScript will help when following this tutorial.

Introduction

One feature that will always make opinion polls stands out and encourage participants, is the fact that their vote counts. Ensuring this can be facilitated by realtime update of points and visualization of data (for example on a chart) depending on choice or votes.

Instant result, live update, realtime apps with less code and many more are some of the promises of Pusher, which it has so far lived up to.

Together in this tutorial, we will build:

This is a simple but yet an effective demonstration of realtime functionality of a basic human activity. Its an app that allows users to cast votes for their favorite mobile device. It contains two different sections:

  1. Where users can select a device.
  2. A chart to display the results as they come in.

This realtime opinion poll will be built using Nest.js and powered by Pusher.

What exactly is Nest.js

Nest.js is a progressive framework for building efficient and scalable server-side applications. Built to take the advantage of modern JavaScript, but still preserves compatibility with pure JavaScript.

Prerequisites

A basic understanding of TypeScript and Node.js will help you get the best out of this tutorial. It is assumed that you already have Node and npm installed. Kindly check Node.js and npm for further instructions and installation steps.

As we proceed in this tutorial, we will make use of some other tools like:

  • Pusher: a Node.js client to interact with the Pusher REST API
  • Axios: a promise-based HTTP client that works both in the browser and in a Node.js environment.
  • CanvasJS: a responsive HTML5 Charting library for data visualization.

Setting up the project

For the purpose of setting up the project, we’ll run the command below to clone the starter repository from Github. This will create a new project folder named nest-poll-application on our machine. We’ll then proceed by changing directory into the newly created project folder and install all the required dependencies for this application. Open your terminal and run:

    // Clone starter repository
    $ git clone https://github.com/nestjs/typescript-starter.git nest-poll-application

    // change directory
    $ cd nest-poll-application

    // install dependencies
    $ npm install

Run the application

Start the development server with :

    $ npm start

The command above will start the application on the default port used by Nest.js. Open your browser and navigate to http://localhost:3000. You should see a welcome message like what we have below:

Pusher account setup

Head over to Pusher and sign up for a free account. This is important as it is required before you can have access to an API key and easily access all the awesome features offered by Pusher.

Create a new app by selecting Channels apps on the sidebar and clicking Create Channels app button on the bottom of the sidebar:

Configure an app by providing basic information requested in the form presented. You can also choose the environment you intend to integrate Pusher with for a better setup experience:

You can retrieve your keys from the App Keys tab:

Bootstrap the application

Under the hood, Nest uses Express library and therefore, favors the popular MVC pattern. In order to create a simple MVC app, we have to install a template engine.

    $ npm install ejs --save

Once the installation process is completed, configure the express instance by updating main.ts file with the content below:

    // ./src/main.ts

    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';

    import * as express from 'express';
    import * as path from 'path';

    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      app.use(express.static(path.join(__dirname, 'public')));
       app.set('views', __dirname + '/views');
       // set ejs as the view engine
       app.set('view engine', 'ejs');
      await app.listen(3000);
    }
    bootstrap();

This is the entry point of the application and necessary for bootstrapping Nest.js apps. I have included the Express and Path modules and set up ejs as the view engine for the application.

Set up the homepage

The views folder will contain all template for this application. Go ahead and create it within the src folder. Once you are done, create a new file named index.ejs right inside the newly created views folder and update the content with:

    // ./src/views/index.js

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <title>Realtime Polling</title>
    </head>
    <body>
        <div class="main">
            <div class="container">
                <h1>Vote for your favorite device</h1>
                <div class="col-md-12">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="poll-device">
                                <img src="/images/infinix.jpg" alt="" id="Infinix">
                                <p class="text-center caption">Infinix</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="poll-device">
                                <img src="/images/nokia.jpg" alt=""  id="Nokia">
                                <p class="text-center caption">Nokia</p>
                            </div>
                        </div>

                        <div class="col-md-3">
                            <div class="poll-device">
                                <img src="/images/samsung.jpg" alt=""  id="Samsung">
                                <p class="text-center caption">Samsung</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="poll-device">
                                <img src="/images/techno.jpg" alt="" id="Techno">
                                <p class="text-center caption">Techno</p>
                            </div>
                        </div>
                    </div>

                    <div id="vote-chart-container"></div>
                </div>
            </div>
        </div>
        <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
        <script src="https://js.pusher.com/4.1/pusher.min.js"></script>   
        <script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>  
        <script src="/vote.js"></script>
    </body>
    </html>

This will render the polling screen with images of devices that users will select from. You can download the images here or use your preferred images. To help out with layout we included bootstrap within the header section of the page. And just before the closing tag of the <body> element we included the CDN file for jQuery as it is a requirement for Canvas.js. We also added a CDN file each for Axios and Pusher and finally, we included a custom script named vote.js.

Route for the homepage

The controller layer in Nest.js is responsible for receiving an incoming request and returning the appropriate response to the client. Nest uses a Controller metadata @Controller to map routes to a specific controller. The starter project already contain a controller by default. We will make use of this in order to render the home for this app. Open .src/app.controller.ts and edit as shown below:

    // ./src/app.controller.ts 

    import { Get, Controller, Res } from '@nestjs/common';
    @Controller()
    export class AppController {
      @Get()
      root(@Res() res) {
        res.render('index');
      }
    }

This controller will ensure that Nest maps every / route to the index.ejs file.

Stylesheet

Create a new folder called public within the src folder and create a new file named style.css within it. Update it with the content below:

    @import url('https://fonts.googleapis.com/css?family=Spectral');
    *, *:before, *:after {
      box-sizing: border-box;
    }

    html, body {
      font-family: 'Spectral', serif;
      height: 100%;
    }
    .main {
      height: 100%;
      background-color: #FAFAFA;
    }
    .container {
      padding-top: 20px;
      padding-bottom: 20px;
    }
    h1 {
      text-align: center;
    }
    .caption {
        font-weight: bold;
    }

    .poll-device {
      margin: 20px;
      padding: 20px;
      border: 1px solid #EDEDED;
      transition: background 500mms ease-in-out;
    }

    .poll-device.selected {
      background: #EDEDED;
    }

    .poll-device:hover {
      background: #EDEDED;
      cursor: pointer;
    }


    .poll-device img {
      width: 100%;
      height: auto;
      display: block;
      margin: 0 auto;
    }

    #vote-chart-container {
      min-height: 370px;
       width: 100%;
       background: #f5f5f5;
    }

Don’t forget to include this file in index.ejs

    <head>
    ...
      <link rel="stylesheet" href="/styles.css">
    </head>

Render the chart

We will attach the chart to a div with an id of vote-chart-container, which we have already added to index.ejs:

    // ./src/views/index.ejs

    <div class="main">
        <div class="container">
        ...
        // chart will be rendered here
        <div id="vote-chart-container"></div>
        ..
        </div>
    </div>

Initialize the chart

Initialize the chart with a default dataset. Because this is a simple example, we won’t bother with persisted data, rather we can just start at empty(zero). So create a new file named vote.js and save it in the public folder. Then proceed to add the content below to initialize the chart:

     // ./src/public/vote.js

    let dataPoints = [
        {label: 'Infinix', y:0},
        {label: 'Nokia', y:0},
        {label: 'Samsung', y:0},
        {label: 'Techno', y:0}
    ]

    const chartContainer = document.querySelector('#vote-chart-container');

    if (chartContainer) {
        const chart = new CanvasJS.Chart('vote-chart-container', {
            animationEnabled: true,
            theme: 'theme1',
            title: {
                text: 'Favorite device'
            },
            data: [
                {
                    type: 'column',
                    dataPoints: dataPoints
                }
            ]
        });

        chart.render();

        // Here, we will configure pusher, subscribe to event and update chart
        ...
    }
  • The dataPoints array is the data source for the chart. The objects in the array have a uniform structure of label, which stores the frameworks and y which stores the points.
  • We check if the chartContainer exists before creating the chart.
  • We use the Chart constructor function to create a chart by passing the configuration for the chart which includes the data. The chart is rendered by calling render() on constructor function instance.

Send the vote request

When a voter clicks on a device, we want to identify the item that was selected and trigger an HTTP request to send their vote request to the server.

    // ./src/public/vote.js


    const app = {
        sendToServer(id){
            let baseURL = 'http://localhost:3000';
            axios.post(`${baseURL}/vote`, {id})
            .then( response => console.log('Successful'));
        },

        start(){
            devices = document.querySelectorAll('.poll-device');
            devices.forEach((item, index) => {
                item.addEventListener('click', (e) => {
                    this.sendToServer(e.target.id);
                });
            });
        }
    };

    window.addEventListener('load', () => app.start());

    let dataPoints = [
        ...
    ]

    const chartContainer = document.querySelector('#vote-chart-container');

    if (chartContainer) {
       ...
        });

        chart.render();
        // Here, we will configure pusher, subscribe to event and update chart
        ...
    }

Create a controller

Earlier, we already configured the app.controller.ts to render the homepage and display the form for consumers. The next thing we need to do is build the controller that will handle the data posted to the server. Create a new folder named vote in the src folder and create a new file called vote.controller.ts within it. Then update it with the content below:

    // ./src/vote/vote.controller.ts

    import { Controller, Post, Res, Body, HttpStatus } from '@nestjs/common';
    import { VoteService } from './vote.service';

    @Controller('vote')
    export class VoteController {
        constructor(private voteService: VoteService){}

        @Post()
        castVote(@Res() res, @Body() vote) {
            this.voteService.create(vote);
            res.status(HttpStatus.OK).send('Voted');
        }

    }

This controller handles only the HTTP request and abstract the logic of Pusher to a service. Let’s create the service next.

Realtime service

To enable realtime updates of the votes, we will integrate Pusher. To achieve a realtime two-way functionality, Pusher needs to be installed both on the client side and on the server side. We already included the script for the client side earlier within our index.ejs file. For the server side lets use Node Package Manager to install the library.

    $ npm install pusher --save

Once the installation is completed, create a new file within ./src/vote called vote.service.ts and update the content with:

    // ./src/vote/vote.service.ts

    import { Component } from '@nestjs/common';

    @Component()
    export class VoteService {
        create(vote) {
            const Pusher = require('pusher');
            var pusher = new Pusher({
                appId: 'APP_ID',
                key: 'YOUR_API_KEY',
                secret: 'YOUR_SECRET_KEY',
                cluster: 'CLUSTER',
                encrypted: true
              });
              pusher.trigger('poll', 'vote', {
                  points: 10,
                  phone: vote,
              });
        }
    }

Here we have initialized Pusher with the required credentials so we’ll be able to trigger an event named vote through a poll channel. Don’t forget to replace the APP_ID , YOUR_API_KEY, YOUR_SECRET_KEY and CLUSTER with the appropriate details obtained from your dashboard.

For the payload, we have a JS object. This object contains the points for each vote and the name of the device being voted.

Register the controller and component

At the moment, our application doesn’t recognise the newly created controller and service. Lets change this by editing our module file 'app.module.ts' and put the controller into the 'controller' array and service into 'components' array of the '@Module() decorator respectively.

    // ./src/app.module.ts

    import { VoteService } from './vote/vote.service';
    import { VoteController } from './vote/vote.controller';
    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';

    @Module({
      imports: [],
      controllers: [AppController, VoteController],
      components: [VoteService],
    })
    export class AppModule {}

Listen for Pusher Channel events and update chart

We can now listen for Pusher events and update the chart with the payload sent to the channel we are subscribed to:

     // ./src/public/vote.js
     ...
    if (chartContainer) {
        ...
        // Here, we will configure pusher, subscribe to event and update chart
        var pusher = new Pusher('YOUR_API_KEY', {
            cluster: 'CLUSTER',
            encrypted: true
        });

        var channel = pusher.subscribe('poll');
        channel.bind('vote', (data) => {
            dataPoints = dataPoints.map(x => {
                if (x.label == data.phone.id) {
                    x.y += data.points;
                    return x;
                } else {
                    return x;
                }
            });
            chart.render()
        });
    }
  • We configure Pusher with our credentials by passing the app key and config object as arguments to the Pusher constructor function.
  • The name of our trigger is poll, so we subscribe to it and listen to its vote event. Hence, when the event is triggered, we update the dataPoints variable and re-render the chart with render()

Conclusion

We just built a very simple realtime poll app powered by Pusher. I hope you found this tutorial helpful and will easily applied the knowledge gained here to improve existing project and new ones.

The source code for this demo can be found here on Github.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.