This article is another entry in our series about integrating the TalkJS chat API with different backends. Today, it is all about shipping a full-fledged chat feature for any NodeJS app. Similar to the previous articles you can find here, we set up a NodeJS server that consists of specific endpoints to get user data as well as store user data and then use this to initialize a chat. The chat uses the same data as the previous articles, so it is very easy to relate. The entire source code is always available on GitHub.
NOTE: This is a barebones example of integration and is to help you get started. When using in a production setting, ensure that users are authenticated and authorized to use the services. We are using an embedded database, which is only for the scope of this tutorial. For production scenarios, you must use a full-fledged database.
Installing the dependencies
To create an empty npm project, use the command npm init -y
. The argument -y sets defaults for the parameters inside package.json. Once created, you can start downloading the dependencies. Make sure you add the parameter "type":"module"
inside the package.json
file to use ES6 style import statements.
We have 4 dependencies that we need for this demo project. They are cors, body-parser, express, lowdb
. Express is our go-to choice for creating APIs with NodeJS and body-parser automatically parses your request so that it becomes easy to handle them in our code. LowDB is an embedded database, similar to the ones we used in our Spring Boot and Flask tutorials, but here it is stored in a JSON file. CORS is to enable cross-origin resource sharing.
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import { LowSync, JSONFileSync } from 'lowdb';
After installing them, create a file called server.js
and import them into the application.
LowDB – Easy to use, embedded database for JavaScript
LowDB is an open-source embedded database for JavaScript, and their GitHub page has very comprehensive documentation on how to get started with examples.
const adapter = new JSONFileSync('file.json');
const db = new LowSync(adapter);
db.read();
db.data ||= { users: [] };
To create a simple JSON database, we use the JSONFileSync function and pass in the required filename. If it is not present, LowDB creates it for you. We then pass that to the LowSync method to get an instance of the database in memory. Note that the Sync in the functions means synchronous. There are also asynchronous variants of these functions. By default, we create an empty array of users inside the database.
Creating the APIs
Before creating the APIs, we must initialize our Express application and configure body-parser. For that, we use the below code.
const app = express();
const port = 3000;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Once that is set, we are good to start creating our APIs. As usual, we have one API for creating the user and one for getting the user data to our frontend.
Create User API
Creating a user is a POST request. We receive all the parameters from the request body and set it to variables. To make it shorter, we can directly assign them when we push it to the database as well.
app.post('/createUser', (req, res) => {
const id = req.body.id;
const name = req.body.name;
const email = req.body.email;
const photoUrl = req.body.photoUrl;
const role = req.body.role;
console.log(id, name, email, photoUrl, role);
db.data.users.push({
id: id,
name: name,
email: email,
photoUrl: photoUrl,
role: role,
});
db.write();
res.status(200).send('User created successfully');
});
Once all the data is ready, we use the statement, db.data.users.push
and pass in an object with the values. This does not persist in the file, so we finally need to use the db.write()
method.
Get User API
This is a much easier API to get the value of the user. We pass in the id in the URL and then retrieve the record from our JSON file with the id. We use the find
method and pass in an arrow function to go through each entry and retrieve the record.
app.get('/getUser/:id', (req, res) => {
const id = req.params.id;
let record = db.data.users.find(p => p.id === id);
if (!record) {
console.log("No data found!");
} else {
console.log("== Record found ==");
console.log(record);
res.status(200).send(record);
}
});
Once retrieved, we send the record to the frontend, where it displays the user information in the chat.
Conclusion
We use the same code as we did for the previous articles for the front end. The only change required is for the getUser
API that needs the userId
in the following format.
http://127.0.0.1:3000/getUser/1
instead of http://127.0.0.1:8080/getUser?id=1
Once you make that change and deploy the frontend, it should pull the information from the server as long as the data is present. To add data, you can use the /createUser
API. You can check out the entire source code at GitHub. Until the next tutorial, happy coding!
Top comments (0)