Real Time Apps with TypeScript: Integrating Web Sockets, Node & Angular

Building a Real Time Chat app from scratch using TypeScript

Luis Aviles
DailyJS

--

Some time ago I implemented a simple chat application using TypeScript language only. The main goal was to write a demo to explain how you can use this programming language on the client side and on the server. The client app is using latest Angular features.

In this post I will show you how I implemented the app from scratch.

Demo: TypeScript Chat Application

What is a Real Time Application?

According this Wikipedia definition, a real-time application allows information to be received as soon as it is published, rather than requiring a source to be checked periodically for updates. Therefore, this kind of app should give a feeling to users that events and actions happen immediately.

WebSockets

WebSockets is a protocol that provides a bi-directional communication channel. This means that a browser and web server can maintain real-time comms, sending messages back and forth while the connection is open.

Websockets communication

Application Structure

We will separate server related code and client code. I will go into details when most important files will are explained. For now, this is the expected structure of our application:

server/
|- src/
|- package.json
|- tsconfig.json
|- gulpfile.js
client/
|- src/
|- package.json
|- tsconfig.json
|- .angular-cli.json

Server Code

Since WebSockets is a specification, we can find several implementations about it. We can choose J̶a̶v̶a̶S̶c̶r̶i̶p̶t̶ TypeScript or any other programming language.

In this case we’ll use Socket.IO, which is one of the fastest and most reliable real-time engines.

Why use TypeScript on server side code?

TypeScript comes with really cool features and it is updated very often. It can prevent about 15% of bugs. Do you need more reasons? 😄

Initializing server application

Create a package.json file and then install the following dependencies:

npm install --save express socket.io @types/express @types/socket.io

We’ll need to install some devDependencies to allow integrate gulp and typescript so that we can define build tasks easily with these tools later:

npm install --save-dev typescript gulp gulp-typescript

TypeScript Compiler Configuration

Create a tsconfig.json file with the following content:

Data Model definition

Taking advantage of static typing, let’s define a small data model as follows:

..let’s see further details into our server/src directory:

server/
|- src/
|- model/
|- message.model.ts
|- user.model.ts
|- index.ts
|- server.ts
|- package.json
|- tsconfig.json
|- gulpfile.js

Chat Server Implementation

The main files in server directory are index.ts and chat-server.ts. The first one allows us to create and export our ChatServer app, while the last one contains express and socket.IO configurations:

Server Classes

The previous code will give a result of the following classes and relationships:

Server classes diagram

Build and Run the Server

In order to have JavaScript files needed by the V8 engine of Node.js, we can add a build task into our gulpfile.js file:

As you can see, the output of build process(JavaScript files) will be located indist directory. To perform this action, you’ll need to run:

gulp build

Now we can run node dist/index.js command to have the server running.

Client Code

Let’s generate our client directory using the latest Angular CLI version:

ng new typescript-chat-client --routing --prefix tcc --skip-install

Then install your dependencies running npm install(I prefer to use Yarn for this step):

cd typescript-chat-client
yarn install

Adding Angular Material

Find and follow the latest guide to install Angular Material inside your Angular CLI project.

As part of using best practices in our project structure, we can create shared and materialmodules:

client/
|- src/
|- app/
|- chat/
|- shared/
|- material/
|- material.module.ts
|- shared.module.ts

|-app.module.ts

We can do that from the command line interface:

ng generate module shared --module app
ng generate module shared/material --module shared

Check the changes inside app.module.ts and shared.module.ts to see the relationships created between these modules.

Adding express and socket.IO

We’ll need to add express and socket.io modules into our client App:

npm install express socket.io --save

Chat Modules and Components

Let’s create a new module before starting to create components for our chat application:

ng generate module chat --module app

Now add a component into newest module:

ng generate component chat --module chat

In order to use web-sockets and custom models, let’s create another shared folder. This time inside chat directory:

ng generate service chat/shared/services/socket --module chat
ng generate class chat/shared/model/user
ng generate class chat/shared/model/message

We’ll be ending with a structure similar to:

client/
|- src/
|- app/
|- chat/
|- shared/
|- model/
|- user.ts
|- message.ts
|- services/
|- socket.service.ts

|- shared/
|-app.module.ts

Observables and Web Sockets

Since our Angular app comes with RxJS, we can use Observables to catch Socket.IO events:

We’ll need to define some enums to manage Actions and Events in the App:

Now we’re ready to listen to messages from the server:

Material Code & UI events have been omitted in this file

Once ChatComponent gets initialized, the component is going to subscribe to SocketService observables in order to start to receive connection events or incoming messages.

The sendMessage and sendNotification functions are going to send the respective content through the same service. Notifications sent at this time are Rename User and User Joined.

Chat Application features

  • Angular CLI
  • Angular 5
  • Angular Material
  • Validation Forms

Source Code

Find the complete project in this GitHub repository:

github.com/luixaviles/socket-io-typescript-chat

Live Demo

Go through to typescript-chat.firebaseapp.com and open two or more tabs in your favorite browser and start a conversation.

If you liked this post, be sure to share it with your friends or give it a clap. 👏

You can follow me on Twitter and GitHub to see more about my work.

Thank you for reading!
Luis Aviles

--

--

Luis Aviles
DailyJS

Google Developer Expert for Web Technologies and Angular. Speaker, Course Author, Photography and Astrophotography enthusiast. @angularBolivia organizer.