In the previous part of the article series, Build Chat Application On MEA2N Stack – Part One, we built a basic chat application on Node.js platform using Express, Angular 2 and socket.io. In this article, we are going to use MongoDB Atlas for saving our chats and retrieving history whenever user requests it.
In the previous part of the article series, Build Chat Application On MEA2N Stack – Part One, we built a basic chat application on Node.js platform using Express, Angular 2 and socket.io. In this article, we are going to use MongoDB Atlas for saving our chats and retrieving history whenever user will be requested for it.
Prerequisites
Setup MongoDB Atlas
MongoDB Atlas is a cloud-hosted MongoDB service. MongoDB team will perform DB management, setup, and configuration, software patching, monitoring, backups and clustering.
To create MongoDB instance in the cloud, go to https://www.mongodb.com/cloud/atlas. Click on ‘Get Started for free’. Provide your information and get started. If you have already signed up, then login to the site.
Here you will see clusters created by you on the dashboard. To create a cluster, click on ‘Build a New Cluster’. It will pop up the details page. We need to provide Cluster name, MongoDB version, Cloud provider region, and Instance Size. For demo purposes, we are going to use free tier.
After cluster creation, select a cluster and click on ‘Connect’. It will pop up a window where you can provide from which IP Address MongoDB will be accessible. For the demo, I have selected that MongoDB will be accessible from anywhere. Then, click on ‘Connect your Application’.
Implementation – Server side (code updates)
Here we need to update ‘send_message’ event listener for save functionality. We have added call to chatsManager.saveChat() function. Then we have added ‘get_history’ event listener, which will get chat history by calling chatsManager.getHistory() method. It will emit ‘take_history’ event for requested client only. We are ready with server side updates. Now it's time to update client side.
clearChatWindow() and loadChatHistory() functiona are added to component. ‘clearChatWindow()’ will assign empty array to messages property. And loadChatHistory() will emit ‘get_history’ event.
Then, add an event listener for ‘take_history’ event. The response received from the event will be directly assigned to messages property. Response is an array of chats sent from the server.
Now, open app.component.html. And add two buttons, one for clearing chat history and another for requesting chat history. Call clearChatWindow() and loadChatHistory() functions on their clicks respectively.
We are ready with our code. Let’s build an Angular application by executing ‘ng build’ command. Then run ‘node starter.js’ command to start our application.
Open two browsers and hit ‘http://localhost:9696’ from both the browsers. And start chatting…
Pro WPF: Windows Presentation Foundation in .NET 3.0