Nest.js

NestJS is a progressive Node.js framework for building efficient, scalable, and maintainable server-side applications. It uses modern JavaScript, is built with TypeScript (but also enables developers to code in pure JavaScript) and combines elements of Object Oriented Programming (OOP), Functional Programming, and Functional Reactive Programming. Under the hood, NestJS utilizes Express.js, but also provides compatibility with a wide range of other libraries, like e.g., Fastify, allowing for easy use of the myriad third-party plugins which are available.

Module 1: Introduction to Nest.js

Understanding Nest.js

Nest.js is a progressive Node.js framework for building efficient, reliable and scalable server-side applications. It uses progressive JavaScript, is built with and fully supports TypeScript.

Setting Up a Nest.js Project

We'll discuss how to install Nest.js CLI and create a new project using the CLI.

npm i -g @nestjs/cli
nest new project-name

Basic Controller and Module

Learn how to create a basic controller and module in Nest.js.

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}

Module 2: Providers and Services in Nest.js

Understanding Providers

A provider is a fundamental concept in Nest.js. Many of the basic Nest.js classes may be treated as a provider – services, repositories, factories, helpers, and so on.

@Injectable()
class CatsService {
  constructor(private readonly catsRepository: CatsRepository) {}
}

Creating a Basic Service

A services file is where you make your HTTP requests (GET, POST, PUT, DELETE), it is equivalent to the service in Angular.

@Injectable()
class CatsService {
  private readonly cats: Cat[] = [];
  create(cat: Cat) {
    this.cats.push(cat);
  }
  findAll(): Cat[] {
    return this.cats;
  }
}

Module 3: Middleware and Exception Filters in Nest.js

Using Middleware

Middleware is a function which is called before the route handler. Middleware functions have access to the request and response objects, and the next() middleware function in the application’s request-response cycle.

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    console.log('Request...', req);
    next();
  }
}

Exception Filters

Exception filters are a powerful tool for handling exceptions across your whole application. Nest.js provides a layer to handle unhandled exceptions at the routing level.

import { Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';

@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    super.catch(exception, host);
  }
}