DEV Community

C I R L O R M ⚡
C I R L O R M ⚡

Posted on

EDD with event emitters

Building an event-driven application in node.js using event emitters. A built-in module that is core to node.js architecture. The EventEmitter is a class that helps us create a publisher-subscriber pattern in node.js.

We’ll see how to use EventEmitter by building a bus booking application where users can book bus seats and receive an email notification when booking is successful. Getting started, we’ll set up a simple express application with a /book route.

index.js

import express from "express"
import { addTrip } from "./utils"

const app = express()

app.post("/book", (req, res) = {
    const {origin, destination, date} = req.body;

    if (!(origin && destination && date)) {
        res.status(400).send("Invalid request")
    }

    addTrip({
        origin, destination, date
    }).then((response) => {
        if (response.status) {
            // send notification to user
            // we can make a request to an email service (like resend) 
            // to send the user the notification. But this will mean we'll have
            // to wait for a response from resend before sending a response to the client.
            // This makes the response time a bit longer
        } else {
            // somehting went wrong
        }
    }).catch((error) => {
        // an error occured
        res.status(400).send(error.message)
    }).finally(() => {
        res.status(200).send("Request Received")
    })
})

app.listen(3000)
Enter fullscreen mode Exit fullscreen mode

In this simple route, adding the logic to send email notifications directly there will cause our api to be a bit slower. So what we can do is to use an EventEmitter when after adding the trip to our database we emit a named event and a lister will pick the event and send the notification. Here’s how we can add that.

import express from "express"
import EventEmitter from "node:events" // import the EventEmitter class
import { addTrip } from "./utils"

const app = express();
const myEmitter = new EventEmitter(); // We create an instance of the EventEmitter class

// Let's setup a listener to listen for a named event, in this case 'booking'
myEmitter.on("booking", (trip) => {
    // Make the call to your email service to send the email
    console.log(trip)
})

app.post("/book", (req, res) = {
    const {origin, destination, date} = req.body;

    if (!(origin && destination && date)) {
        res.status(400).send("Invalid request")
    }

    addTrip({
        origin, destination, date
    }).then((response) => {
        if (response.status) {
            // emit an event and the listener will pick it up
            let trip = response.data
            myEmitter.emit("book", trip)
        } else {
            // somehting went wrong
        }
    }).catch((error) => {
        // an error occured
        res.status(400).send(error.message)
    }).finally(() => {
        res.status(200).send("Request Received")
    })
})

app.listen(3000)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)