Demistifying Websockets with NodeJS -  part 2

Demistifying Websockets with NodeJS - part 2

Implementing a REST endpoint

Welcome to the second part of this series where we'll talk a bit more about websockets as it relates to a real use case in a node js app.

The use case in this context is a web chat app. We'll focus only on the backend implementation.

To demonstrate the practicality of websockets in real-time communication, let us write a simple endpoint for uploading an image within a chat. Ideally, we'll want all subscribed members to be notified when an image is sent to the group.

So in REST, this endpoint may be represented as so: /upload-image. We'll define a POST route for this in the corresponding routes file.

app.post(/upload/new, ImageValidation, ImageController)

Formidable is a good tool to handle file uploads in an express app hence we'll want to write a controller that takes care of this operation.

const form = new formidable.IncomingForm();

And of course, taking care of any errors along the way.

 form.parse(req, (err, fields, files) => {
    if (err) {
      res.status(500).send('Error uploading image');
      next(err)
    }

To ensure real-time capabilities in the server, it should be designed in a largely event-driven way.

This means that when a user sends a message, the server processes the message and broadcasts it immediately to the client side.

To achieve this in nodejs, we use the socket IO library to emit an event once the file is successfully uploaded.

io.emit('image', { url: `/uploads/${files.image[0].originalFilename}` });

This event is passed to the client and the image is accessed from the payload using the `url` key.

It's important to design the client in way to dynamically handle the data and display corresponding interface without needing a refresh.

In this two-part series, we have talked about websockets and how it caters to the wide range of real-time communication needs of node js applications, as well as a typical workflow process of implementing REST endpoint to complement the real-time prowess of websockets.

By embracing this technology, you can craft sophisticated web applications and deliver compelling user experiences that enhance communication.