51-Nodejs Course 2023: Events: Database Connection Events
Tags: node, typescript, mongodb, fastify
Published: 2022-11-08 15:56:30

---
title: 51-Nodejs Course 2023: Events: Database Connection Events
published: true
description: 
series: Nodejs Course 2023
tags: nodejs, typescript, mongodb, fastify
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nlg8cvr7bwqu1hbsas2t.png
# Use a ratio of 100:42 for best results.
---


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

```ts
// 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);
  }
}
```

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.

```ts
// 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);
  }
}
```

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

```ts
// 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);
});
```

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.

```ts
// 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);
    }
  }
}
```

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.

```ts
// 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);
  }
}
```

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](https://github.com/hassanzohdy/nodejs-2023)

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) 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](https://www.youtube.com/playlist?list=PLGO8ntvxgiZMJc7RN2lIq9WmMOlWZGzmz), 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

* [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)