Build a Real-Time App with Deepstream and Angular

Real-time technologies are gaining momentum, applications that require syncing data not just between multiple clients but also with backend services and databases are on a rise. A popular example would be a trading application, in which response time and real-time syncing are of great importance. Deepstream aims to solve this interesting problem with ease.

In this tutorial, we will see how we can build a real-time app with Deepstream. We will build a real-time timeline application where one user posts an update it would immediately show up to another user connected to the client. We will use Angular 4 to build our front-end.

Setup Deepstream Server

Deepstream can be installed for our OS or can be set up using docker or npm. For our tutorial, we will set it up using npm.

That’s it three lines. Now we can start our Deepstream server by running node server.js.

Setup Angular

I’ll be using angular-CLI to scaffold our application. Angular CLI will make our development easy. We will not go into too many details of setting up our Angular app as that’s not our focal point.

To begin with, we will just have a simple app which displays a timeline and allows the user to add to the timeline. For the demo we won’t have user management, we will just let user type in the username.

This our app looks like.

The user would come in and enter the username and start posting on the timeline. We are just pushing the contents that the user posts and iterating it using the ngFor directive to construct our timeline. You can have a look at the code we have got so far. I have also used [email protected] for a bit of styling.

/* You can add global styles to this file, and also import other style files */.timeline-element{background-color:#eeeeee;border-top:1pxsolid#ccc;}.thumb{margin-top:5px;}

Now, this is very basic. Nothing interesting, It’ time to make our app real-time. Basically what we want to do is, whenever a user enters something into the timeline we wanna make sure it is displayed instantaneously to other users. Deepstream will help us do that.

Going Real-time with Deepstream.io

We already have our Deepstream server running. Now we will integrate Deepstream client into our angular app.

Deepstream provides a JavaScript client SDK which we can use. Let’s first install it. Navigate to your Angular app folder and run…

npm i deepstream.io-client-js --save

Deepstream,Angular, Realtime App
Include it under scripts in our angular-cli.json

We can directly now use the Deepstream client in our component, but it’s better to wrap it into a service.

Create a file named app.service.ts.

app.service.ts

import{ Injectable } from "@angular/core";

declare var deepstream;

@Injectable()exportclass DsService {public ds;

constructor(){this.ds= deepstream('localhost:6020');}}

Note, our Deepstream server is running on localhost:6020.

A brief of records and lists in Deepstream

Records are the basic building blocks in Deepstream, they are nothing buy JSON object as data and a bunch of methods that allow us to watch and listen to them for changes. This means whenever a record is changed Deepstream notifies all it’s connected clients about the changes and syncs it across. Deepstream also allows us to add storage/ cache connectors which will persist the record data in the connected database.

Lists are nothing but a collection of records. Lists only store the names of records it holds. Deepstream also allows us to listen to changes on the list as well.

Going Realtime

Now we are going to make some changes to our component to integrate Deepstream into it.

Import the DsService we created and instantiate it in our constructor.

First, we log-in to our DS server. Deepstream allows us to log in anonymously without using credentials which is enough for our demo app.
Next, we get our list timeline. This list will hold all our status records.

Now since our app may restart when we have new updates or any other reason we need to fetch the existing records and construct our timeline. list.getEntries(); gives us the existing entries then we iterate through the list and subscribe to each record. At last we are adding the records in front of out this.timeline array, which is used to display the data on the UI.

list.on('entry-added', (recordName)={..}) allows us to listen to new entries in the timeline list. This helps us update our Timeline in real-time whenever any user updates his status.

Now, we need to create a new record and add it to our timeline list whenever users post something. Change our addPost() method to look like below.

app.component.ts

/** add a new post to timeline */
addPost(){if(!this.user){returnalert("Enter your name, to proceed.");}

const uid = Math.floor(Math.random()*1000);//temp way for democonst recordName = `status/${uid}`;//create a unique record nameconst record =this.client.record.getRecord(recordName);
record.whenReady(record =>{// data has now been loaded
record.set({
author:this.user,
content:this.userStatus});const list =this.client.record.getList('timeline');
list.addEntry(recordName);//add to the listthis.userStatus="";});}

Each record needs to have a unique name. For the demo, I’m using a simple Math function, but in real app better method like uuid should be used, Deepstream also provides a method getUid to generate unique ids. Once the record is created we set the data and add it to the List.
Now the entry-added listener on each client will listen to this change and update our timeline.

In case you missed anything here is the complete app.component.ts file.

for(let i =0; i<entries.length; i++){this.client.record.getRecord(entries[i]).whenReady(record =>{
record.subscribe(data =>{this.timeline.unshift(data);},true);//true invokes callback for the first time as well.});}

/** add a new post to timeline */
addPost(){if(!this.user){returnalert("Enter your name, to proceed.");}

const uid = Math.floor(Math.random()*1000);//temp way for democonst recordName = `status/${uid}`;//create a unique record nameconst record =this.client.record.getRecord(recordName);
record.whenReady(record =>{// data has now been loaded
record.set({
author:this.user,
content:this.userStatus});const list =this.client.record.getList('timeline');
list.addEntry(recordName);//add to the listthis.userStatus="";});}

/** Sets user's name */
setUser(ev){this.user= ev.target.value;}}

Seeing our app in action

Start you deepstream server by running..

node server.js

Start you Angular app using ..

ng serve

Now open up your app on two browser windows, use an incognito window. You can also run the same Angular client of different ports. Now, enter the username and start updating your status. You should immediately see the status update from one window reflected onto another. Check out the below video for a demo.

Now even if you refresh the page, your timeline will be constructed, this is because we are fetching the records in the list at the time of initializing the component. However, if you restart your Deepstream server, the data will disappear, this is because Deepstream by default stores data in it’s memory, we can persist the data by connecting any database using the Deepstream storage connectors.

Conclusion

In this tutorial, we learned how we can build a Real-time application using Deepstream and Angular. Deepstream is a very powerful tool for real-time syncing of data from our servers to clients, moreover, we can also sync data to a storage engine. This tutorial offered a glimpse of how powerful real-time applications can be, in our further tutorials we will explore other options for building real-time applications.