8-Nodejs Course 2023: Updating Router Layer

hassanzohdy

Hasan Zohdy

Posted on October 29, 2022

8-Nodejs Course 2023: Updating Router Layer

So what we did in our last article is creating a Router layer over Fastify to manage routes, let's continue with that.

Singleton and Encapsulation

We imported our router object in the index like this:

import Router from './router';

const router = Router.getInstance();
Enter fullscreen mode Exit fullscreen mode

We can do a simple step to make it easier to import the router without having to get the getInstance each time.

import { Route } from "./types";

export class Router {
  /**
   * Routes list
   */
  private routes: Route[] = [];

  /**
   * Router Instance
   */
  private static instance: Router;

  /**
   * Get router instance
   */
  public static getInstance() {
    if (!Router.instance) {
      Router.instance = new Router();
    }

    return Router.instance;
  }

  private constructor() {
    //
  }

  /**
   * Add get request method
   *
   * // Method chaining
   */
  public get(path: string, handler: any) {
    this.routes.push({
      method: "GET",
      path,
      handler,
    });

    return this;
  }

  /**
   * Register routes to the server
   */
  public scan(server: any) {
    this.routes.forEach(route => {
      const requestMethod = route.method.toLowerCase();
      const requestMethodFunction = server[requestMethod].bind(server);

      requestMethodFunction(route.path, route.handler);
    });
  }
}

// 👇🏻 we will create it internally here
const router = Router.getInstance();

// 👇🏻 now we export it directly
export default router;
Enter fullscreen mode Exit fullscreen mode

Adding more methods

We will add more methods to our router, we will add post, put, delete and patch methods.

import { Route } from "./types";

export class Router {
  /**
   * Routes list
   */
  private routes: Route[] = [];

  /**
   * Router Instance
   */
  private static instance: Router;

  /**
   * Get router instance
   */
  public static getInstance() {
    if (!Router.instance) {
      Router.instance = new Router();
    }

    return Router.instance;
  }

  private constructor() {
    //
  }

  /**
   * Add get request method
   */
  public get(path: string, handler: any) {
    this.routes.push({
      method: "GET",
      path,
      handler,
    });

    return this;
  }

  /**
   * Add post request method
   */
  public post(path: string, handler: any) {
    this.routes.push({
      method: "POST",
      path,
      handler,
    });

    return this;
  }

  /**
   * Add put request method
   */
  public put(path: string, handler: any) {
    this.routes.push({
      method: "PUT",
      path,
      handler,
    });

    return this;
  }

  /**
   * Add delete request method
   */
  public delete(path: string, handler: any) {
    this.routes.push({
      method: "DELETE",
      path,
      handler,
    });

    return this;
  }

  /**
   * Add patch request method
   */
  public patch(path: string, handler: any) {
    this.routes.push({
      method: "PATCH",
      path,
      handler,
    });

    return this;
  }

  /**
   * Register routes to the server
   */
  public scan(server: any) {
    this.routes.forEach(route => {
      const requestMethod = route.method.toLowerCase();
      const requestMethodFunction = server[requestMethod].bind(server);

      requestMethodFunction(route.path, route.handler);
    });
  }
}

const router = Router.getInstance();

export default router;
Enter fullscreen mode Exit fullscreen mode

Nothing new here, just added the same code for each method.

Getting all routes list

We will add a method to get all routes list, we can use it in debugging or testing.

import { Route } from "./types";
// ...

  /**
   * Get all routes list
   */
  public list() {
    return this.routes;
  }  
Enter fullscreen mode Exit fullscreen mode

And that's it, we are now ready to add any route we want to our server, also we can get it from anywhere in our code.

🎨 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)

💖 💪 🙅 🚩
hassanzohdy
Hasan Zohdy

Posted on October 29, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related