DEV Community

Cover image for 51-Nodejs Course 2023: Events: Database Connection Events
Hasan Zohdy
Hasan Zohdy

Posted on

51-Nodejs Course 2023: Events: Database Connection Events

So we got to know about the events in the previous article. Now we will see how to use the events in the database.

Connection Events

The connection events are used to know the status of the connection. The events are as follows:

  • connected: This event is fired when the connection is established.
  • disconnected: This event is fired when the connection is disconnected.
  • reconnected: This event is fired when the connection is reconnected.
  • error: This event is fired when the connection is not established.

Let's see how to use these events.

Open src/core/database/connection.ts

If you can recall, we have there the connect method which is used to connect to the database.

In that sense, we added a console to display a Connected message when the connection is established.

Here we'll replace this with an event trigger, let's see

// src/core/database/connection.ts
import events from '@mongez/events';

export class Connection {
    // ...

  /**
   * Connect to the database
   */
  public async connect() {
    const { host, port, username, password, name } = this.configurations;

    try {
      this.client = await MongoClient.connect(`mongodb://${host}:${port}`, {
        auth: {
          username: username,
          password: password,
        },
      });

      const mongoDBDatabase = await this.client.db(name);

      this.database = database.setDatabase(mongoDBDatabase);

      // trigger connected event
      this.trigger("connected", this);
    } catch (error) {
      // trigger connection error event
      this.trigger("error", error, this);
      console.log(error);
    }
  }

  /**
   * Trigger a connection event
   */
  protected trigger(eventName: string, ...data: any[]) {
    return events.trigger(`database.connection.${eventName}`, ...data);
  }
}
Enter fullscreen mode Exit fullscreen mode

We have added a trigger method which is used to trigger the events. We have added the connected event in the connect method that will be called once the connection is successfully established.

Also we updated the catch block to trigger the error event if there is an error while connecting to the database.

Now let's add the listen method on.

Listen to Connection Events

We have added the events trigger, but now how can we listen to these events?

We'll create a public method on that allows us to listen to the events.

// src/core/database/connection.ts
// 👇🏻 Update the import to import EventSubscription Type
import events, { EventSubscription } from '@mongez/events';

export class Connection {
    // ...

  /**
   * Listen to a connection event
   */
  public on(eventName: string, callback: any): EventSubscription {
    return events.subscribe(`database.connection.${eventName}`, callback);
  }
}
Enter fullscreen mode Exit fullscreen mode

Now we can use this method from anywhere in our app.

// src/app/users/routes.ts
import { connection } from 'core/database';

connection.on('connected', () => {
  console.log('Connected to the database');
});

connection.on('error', (error) => {
  console.log('Error while connecting to the database', error);
});
Enter fullscreen mode Exit fullscreen mode

We can actually from now on use this instead of our setTimeout function that we always use to test our database code.

Closed COnnection Event

Let's add another event that will be triggered when the connection is closed.

// src/core/database/connection.ts
export class Connection {
    // ...

  /**
   * Connect to the database
   */
  public async connect() {
    const { host, port, username, password, name } = this.configurations;

    try {
      this.client = await MongoClient.connect(`mongodb://${host}:${port}`, {
        auth: {
          username: username,
          password: password,
        },
      });

      const mongoDBDatabase = await this.client.db(name);

      // listen to connection when closed
      this.client.on("close", () => this.trigger("close"));

      this.database = database.setDatabase(mongoDBDatabase);

      // trigger connected event
      this.trigger("connected", this);
    } catch (error) {
      // trigger connection error event
      this.trigger("error", error, this);
      console.log(error);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

We listened to close event of Mongo client and once happens we'll trigger our own close event.

Event Types

Let's be more professional, let's add a type for our events types.

// src/core/database/connection.ts


export type ConnectionEvent = "connected" | "error" | "close";

export class Connection {
  // ...

  /**
   * Trigger a connection event
   */
  protected trigger(eventName: ConnectionEvent, ...data: any[]) {
    return events.trigger(`database.connection.${eventName}`, ...data);
  }

  /**
   * Listen to a connection event
   */
  public on(eventName: ConnectionEvent, callback: any): EventSubscription {
    return events.subscribe(`database.connection.${eventName}`, callback);
  }
}
Enter fullscreen mode Exit fullscreen mode

Now we can autocomplete our events and typescript will complain if we mis wrote the event name.

🎨 Conclusion

In this article, we learned about how to add events to Database Connection, we added three events, connected which is triggered when database is connected successfully, error which is triggered when the connection fails and close when connection is closed.

🚀 Project Repository

You can find the latest updates of this project on Github

😍 Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

🎞️ Video Course (Arabic Voice)

If you want to learn this course in video format, you can find it on Youtube, the course is in Arabic language.

💰 Bonus Content 💰

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

Packages & Libraries

React Js Packages

Courses (Articles)

Top comments (0)