Build a chat app with sentiment analysis using Nest.js
To follow this tutorial you need Node and npm installed on your machine. A basic understanding of TypeScript and Node.js will be helpful.
Introduction
In recent years, sentiment analysis has shifted from analyzing online product reviews to social media texts from Twitter and Facebook. Now with the advent and popularity of chat applications on virtually all web applications around the world, we can use a sentiment analysis tool to add a fun feature that enriches users’ chat experience.
In this post, we will take a dive into a realtime chat demo. This application will be built using Nest.js and Pusher. Nest.js is a Node.js progressive framework for building efficient and scalable server-side applications. In addition, we will also be able to perform sentiment analysis on messages sent by users.
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.
Here is a quick overview of the technologies that we will be using in this post.
- Nest.js: 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.
- 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.
- Sentiment: Sentiment is a module that uses the AFINN-165 wordlist and Emoji Sentiment Ranking to perform sentiment analysis on arbitrary blocks of input text.
- Vue.js: Vue is a progressive JavaScript frontend framework for building web applications.
Setting up the application
The simplest and most efficient way to set up a Nest.js application is to clone the starter repository made available on their website.
Now let’s run a command that will create a new project folder named realtime-chat-nest
on your machine. Open your terminal or command prompt and run this command :
$ git clone https://github.com/nestjs/typescript-starter.git realtime-chat-nest
Go ahead and change directory into the newly created folder and install all the dependencies for the project.
// change directory
cd realtime-chat-nest
// install dependencies
npm install
Start the application
Run the application 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 the page with a welcome message like what we have below.
Server dependencies
Run the command below to install the server dependencies required for this project.
npm install ejs body-parser pusher
-
ejs: this is a simple templating language for generating HTML markup with plain JavaScript.
-
Body-parser: a middleware used for extracting the entire body portion of an incoming request stream and expose it on
req.body
. -
Pusher: a Node.js client to interact with the Pusher REST API
Pusher account setup
Head over to Pusher and sign up for a free account.
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 the Express library and therefore, favors the popular MVC pattern.
To set this up, open up main.ts
file and update it with the content below:
// ./src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as bodyParser from 'body-parser';
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 module, path, and set up ejs as the view engine for the application.
Building the homepage
The views
folder will contain all templates 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.ejs
<!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">
<link rel="stylesheet" href="/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<title> Chat </title>
</head>
<body>
<div id="app">
<div class="row">
<div class="col-md-3" id="active-user">
<div class="form-group">
<h3 v-if="username">Hello {{ username }}</h3>
<div v-else>
<h3>Enter a username</h3>
<input type="text" @Keyup.enter="getUser" placeholder="Username" class="form-control">
</div>
</div>
</div>
<div class="col-md-9" id="chat-room">
<div v-if="username">
<div>
<div style="border-bottom: 1px solid black">
<h2>{{ username }}</h2>
</div>
<div v-for="chat in chats" id="chat-box">
<p> {{chat.mood}} </p>
<p> <b>{{ chat.user }}</b></p>
<p id="chat-message"> {{ chat.message }} </p>
</div>
</div>
<div class="form-group">
<textarea placeholder="Type a message here then hit ENTER" @Keyup.enter="postMessages"></textarea>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.js"></script>
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script src="/main.js"></script>
</body>
</html>
On this page, we are simply building a basic chat room that will showcase the realtime functionality and sentiment analysis that was mentioned earlier. This will serve as the homepage for the application, hence the need for it to be well structured.
Firstly, we included a link to the Bootstrap CDN file to add some default styling and layout to our application. We also added a custom stylesheet for further styling. We will create this stylesheet in the next section. Also included in a <script>
tag just before the page title is a CDN file for Vue.js. This is to ensure that Vue.js is loaded immediately the index.ejs
file is rendered.
Furthermore, on this page, we used an event handler to listen to keyboard events using key modifiers aliases made available by Vue.js. This process will be discussed later in the tutorial.
Finally, we included CDN file each for Axios
, Pusher
and then proceeded to add a custom script file named main.js
. To set up this file, go ahead and create a public
folder within the src
folder in the application and create the main.js
file within it.
Stylesheet
To set up this stylesheet, locate the public
folder and create a new file named style.css
within it. Next, open the file and paste the code below:
// ./src/public/style.css
html{
height: 100%;
}
#active-user {
height: 600px;
background: #000000;
color: #ffffff;
min-height: 600px;
display: flex;
align-items: center;
justify-content: center;
}
#chat-room {
min-height: 600px;
background: #f5f5f5;
}
textarea {
position: absolute;
bottom: 10px;
width: 600px;
min-height: 120px;
padding: 20px;
border: none;
overflow: auto;
outline: none;
}
#chat-box {
padding: 20px;
}
#chat-message {
background: #f8f9fa!important;
max-width: 40%;
min-height: 50px;
padding: 3px;
}
Handling routes
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 contains 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 index.ejs
file.
Initialize the chat room
As carefully laid out on our index.ejs
page earlier on, the chat room will contain two separate sections that will be differentiated by the width of the column. One of the sections will contain an input field that will accept a username and the other section will be where the chat messages are properly displayed.
To initialize the chat room, we will start by creating a new Vue instance with the Vue function. Open up the main.js
file created earlier and paste the code below in it:
// ./src/public/main.js
new Vue({
el: '#app',
data: {
chats: [],
username: "",
mood: ''
},
methods: {
getUser(event) {
this.username = event.target.value;
}
...
}
})
Here, we created a Vue instance and as part of the options, we bound Vue to a div with an id of app
and also passed data options. Further down, we used a method getUser()
to retrieve the username of a user.
Post a message
// ./src/public/main.js
new Vue({
el: '#app',
data: {
chats: [],
username: "",
mood: ''
}
methods: {
getUser(event) {
...
},
postMessages(event) {
const chatMessage = event.target.value;
if(event.keyCode === 13 && !event.shiftKey) {
const chat = {
user: this.username,
message: chatMessage
};
event.target.value = "";
axios.post('/message', chat)
.then( data => {
console.log(data);
});
}
}
}
})
In order to send the chat message to the server, we created a postMessages()
function with the responsibility of retrieving the chat message provided by a user and sending it to the server.
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 chat
in the src
folder and create a new file called chat.controller.ts
within it.
// ./src/chat/chat.controller.ts
import { Controller, Post, Res, Body, HttpStatus } from '@nestjs/common';
import { ChatService } from './chat.service';
@Controller('message')
export class ChatController {
constructor(private chatService: ChatService){}
@Post()
postMessage(@Res() res, @Body() data ) {
this.chatService.addMessage(data)
res.status(HttpStatus.OK).send("Comment posted successfully")
}
}
As shown above, we imported ChatService
and injected it into the controller through the constructor. As recommended by Nest a controller should handle only HTTP requests and abstract any complex logic to a service.
Realtime service with Pusher
As required within the ChatController
above, let’s create a component as a service. This will basically receive the posted data
object that contains, both the username and chat messages provided by the active user and publish it to a designated channel for the client side to listen and subscribe to.
Furthermore, we’ll use the Sentiment javascript library for analysis. To install this library, open a terminal in the root folder of your project and run the following command.
npm install sentiment --save
Once the installation process is completed, create a new file within chat
folder named chat.service.ts
// ./src/chat/chat.service.ts
import { Component } from '@nestjs/common';
const Sentiment = require('sentiment');
@Component()
export class ChatService {
addMessage(data) {
const Pusher = require('pusher');
const sentiment = new Sentiment();
const sentimentScore = sentiment.analyze(data.message).score;
const chat = {
user: data.user,
message: data.message,
sentiment: sentimentScore
}
var pusher = new Pusher({ // replace with valid credentials
appId: 'YOUR_APP_ID',
key: 'YOUR_API_KEY',
secret: 'YOUR_SECRET_KEY',
cluster: 'CLUSTER',
encrypted: true
});
pusher.trigger('chats', 'new-chat', chat);
}
}
Here we have initialized Pusher with the required credentials in order to be able to trigger an event named new-chat
through a channel named chats.
We also required Sentiment module, this is important, as it will help us analyze the data messages posted by a user and returned respective scores by cross-checking the words.
Connecting the dots
To make this work, both the ChatController
and ChatService
needs to be registered within the app.module.ts
file.
// ./src/app.module.ts
import { ChatController } from './chat/chat.controller';
import { ChatService } from './chat/chat.service';
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
@Module({
imports: [],
controllers: [AppController, ChatController],
components: [ChatService],
})
export class AppModule {}
Restart the development server if it is currently running. Check your page on http://localhost:3000. You should see:
If we try to send a message, nothing will happen for now. This is because we have not updated the chat room with the values of the chat posted from the server.
Displaying chat messages
In order to receive the chat messages in realtime, we’ll use the subscribe()
method from Pusher to subscribe to the created chats
channel.
// ./src/public/main.js
const SAD_EMOJI = [55357, 56864];
const HAPPY_EMOJI = [55357, 56832];
const NEUTRAL_EMOJI = [55357, 56848];
new Vue({
el: '#app',
data: {
...
},
created() {
let pusher = new Pusher('YOUR_API_KEY', {
cluster: 'CLUSTER',
encrypted: true
});
const channel = pusher.subscribe('chats');
channel.bind('new-chat', data => {
const expression = data.sentiment > 0 ? HAPPY_EMOJI : (data.sentiment === 0 ? NEUTRAL_EMOJI : SAD_EMOJI);
const response = {
message: data.message,
user: data.user,
mood: String.fromCodePoint(...expression)
}
this.chats.push(response);
});
},
methods: {
getUser(event) {
..
},
postMessages(event) {
...
}
}
})
First, we added some constants of code points for a particular sentiment emoji. This will help us rendered an emoji corresponding to the mood of the user during the chat as analyzed by the Sentiment module.
Ensure that you replace the YOUR_API_KEY
placeholder with the appropriate credentials as obtained from your user’s dashboard on Pusher.
You can go ahead now and give this a try by restarting the development server:
Conclusion
We have been able to build a basic chat application with realtime functionality as powered by Pusher. A lot of improvement can be introduced in order to make this application function much better. Please feel free to explore by checking the source code of this project here on Github.
I hope you found this tutorial helpful.
6 May 2018
by Christian Nwamba