Author avatar

Christian Nwamba

Build a Simple Serverless Clock Using Realtime Events in 5mins

Christian Nwamba

  • Jan 10, 2019
  • 6 Min read
  • 3,913 Views
  • Jan 10, 2019
  • 6 Min read
  • 3,913 Views
Node.js

Introduction

Whenever we work in the arena of web development, we try to simplify our solutions as much as possible to make them more usable and easier to develop. "Serverless" concepts and realtime stores exemplify such simplification. These ideas improve how we work, reduce boilerplate code, and most importantly assure peace of mind to the developer.

This article will exhibit the simplicity of using stdlib and deepstreamHub to build a clock application. The clock will retrieve time information from the server, then relay it to the browser for rendering.

stdlib and "serverless"-ness

stdlib is an implementation of the "serverless" concept. As commonly mistaken, "serverless" does not mean "no servers;" it just means that we don't have to handle the server details and operations to be productive. Taking the "serverless" route, a developer can write functions that deploy and result in an API endpoint. You can read more about serverless technology on its Wikipedia page

Setting Up stdlib

Now its time to set everything up using our favorite tool -- if you guessed npm* (Node Package Manager), you are correct. Before that though, you need to create an stdlib account that links you to functions/services that you will need down the line.

Once your account has been created, use npm to install the CLI (Command Line Interface) tool for interacting with your account. The CLI tool simplifies creating, running, and deploying functions:

1npm install lib.cli -g
bash

You need to create a workspace. A workspace is a directory in which a group of functions registered under a given user live. Creating a workspace is as simple as making a directory:

1mkdir your-workspace-name
bash

In your workspace, initialize stdlib by authenticating with the credentials you created while signing up:

1lib init
bash

Right now, your machine has been mapped to your account. You can then create a new service/function and hope to sync with your stdlib server:

1lib create clock
bash

This creates a directory named clock which contains a main folder that contains your function. The index.js file contains a boilerplate function that you can run to see an example of how stdlib works:

1lib http
bash

The above command will serve your function locally at localhost:8170 by default.

deepstream for Realtime PubSub

stdlib is capable of converting your functions to API endpoints. Although this feature is organizationally handy for users and developers alike, "endpoints need to be static". Which means that stdlib's API endpoints are problematic if you need to send some realtime data. With deepstream, however, realtime data transfer has never been easier. We will use deepstream's PubSub feature to emit realtime events from our stdlib function.

You will need to create a free deepstreamHub account which generates an API key to interact with the server.

First, let's install deepstream client on to our clock function:

1npm install --save deepstream.io-client-js
bash

Import deepstream to main/index.js:

1const ds = require("deepstream.io-client-js");
js

Create a deepstream instance with the deepstreamHub URL and log in as anonymous to start communicating with the sever:

1const ds = require("deepstream.io-client-js");
2
3module.exports = (params, callback) => {
4  const client = ds("<APP-URL>").login();
5  callback(null, "hello world");
6};
js

You can start emitting events through the object represented by the client variable. We are building a clock, therefore, the best way to emit events at intervals is to use the setInterval method:

1const ds = require("deepstream.io-client-js");
2const moment = require("moment");
3
4module.exports = (params, callback) => {
5  const client = ds("<APP-URL>").login();
6  setInterval(() => {
7    client.event.emit("time", moment().format("MMMM Do YYYY, h:mm:ss a"));
8  }, 1000);
9
10  callback(null, "hello world");
11};
js

We've also imported moment to help us format time. An example format would look like the following:

1May 1st 2017, 7:26:39 AM

Subscribing via a Client

Right now, at the /clock route, our logic emits a realtime data via web socket. We can consume this realtime data from anywhere as long as we have the connection URL from deepstream.

We can do this by importing deepstream from CDN (Content Delivery Network), logging in, and logging the emitted events to the console:

1<html>
2
3  <body>
4
5    <script src="https://code.deepstreamhub.com/js/2.x/deepstream.min.js"></script>
6    <script>
7	    var client = deepstream('APP-URL')
8
9		client.login()
10
11		client.event.subscribe('time', time => {
12		  console.debug(time)
13		})
14    </script>
15  </body>
16</html>
html

Rather than emitting, we subscribe to the time event and log the payload whenever the event gets emitted:

Image of console

We can display the time in the browser instead of printing it to the console:

1var client = deepstream("APP-URL");
2
3client.login();
4
5var timeP = document.getElementById("time");
6client.event.subscribe("time", time => {
7  timeP.innerHTML = time;
8});
js

Conclusion

Hopefully, you have a learned a quicker way to build realtime (and static) web apps. The clock example is basic, but should help you if you're dealing with a more complex project. Realtime data stores and serverless ideology have unimaginable powers that you can harness to make your applications more reliable and flat-out cooler.


Thanks for reading!