4. NestJS

What is NestJS?

NestJS is a progressive Node.js framework for building efficient, scalable, and maintainable server-side applications. It leverages TypeScript by default (while still supporting JavaScript), and is heavily inspired by Angular’s architecture, incorporating features like dependency injection, decorators, and modular design. Built on top of Express (with optional support for Fastify), Nest provides a structured and opinionated way to develop robust backend applications, making it ideal for enterprise-level projects, RESTful APIs, microservices, and GraphQL-based systems. Its powerful CLI, rich ecosystem, and seamless integration with tools like TypeORM, Prisma, and Swagger make it a popular choice for modern backend development.

Running nest

To run nest use the command: npm run start:dev

Understanding Nest

For each Nest folder, it containst three files, a service, a controller and a module. Understanding these three parts are key to capitalising Nest's modular design.

Service:

A Servicearrow-up-right is a class that contains your business logic, database interactions, and other key logic. You can treat the service class as a regular python class that is in charge of creating all the necessary methods to perform data operations. When using Prisma, all service methods must be asynchronous. Services are where you:

  • Fetch data from a database

  • Perform complex calculations

  • Connect to third-party APIs

  • Manage your core application logic

An example service class for an employee would look like this.

employee.service.ts
import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { DatabaseService } from 'src/database/database.service';

@Injectable()
export class EmployeeService {
  constructor(private readonly databaseService: DatabaseService) {}
  async create(createEmployeeDto: Prisma.EmployeeCreateInput) {
    return this.databaseService.employee.create({ data: createEmployeeDto });
  }

  async findAll(role?: 'INTERN' | 'ENGINEER' | 'ADMIN') {
    if (role) {
      return this.databaseService.employee.findMany({
        where: { role },
      });
    }
    return this.databaseService.employee.findMany();
  }

  async findOne(id: number) {
    return this.databaseService.employee.findUnique({
      where: { id },
    });
  }

  async update(id: number, updateEmployeeDto: Prisma.EmployeeUpdateInput) {
    return this.databaseService.employee.update({
      where: { id },
      data: updateEmployeeDto,
      });
  }

  async remove(id: number) {
    return this.databaseService.employee.delete({
      where: { id },
    });
  }
}

Controller

A Controllerarrow-up-right defines the HTTP endpoints for your app. It’s responsible for handling requests (like GET, POST, PUT, DELETE) and returning responses. Each method in the controller corresponds to a route in your API, and will have a decorator (e.g. @GET()) followed by the actual method (in the next line). Controllers handle HTTP requests, but all logic is offloaded to services to keep the controller clean and focused.

A list of these Decoratorsarrow-up-right:

@Module() Defines a Module and registers controllers and providers.

@Controller() Defines a Controller and its base route.

@Get(), @Post(), @Patch()... Map HTTP methods to controller methods.

@Injectable() Marks a class as a service that can be injected.

@Param() Extracts URL parameters (e.g., :id).

@Body() Extracts data from the request body.

@Query() Extracts query parameters (e.g., ?page=2).

A sample Controller file for an employee database table may look like this:

Here, @Controller('employee') means that all of the HTTP queries are unique to the URL that ends in /employee/.

Module

A Modulearrow-up-right is a class that organises related parts of your application. Each feature (e.g., Users, Auth, Products) typically has its own module.

Modules are defined using the @Module() decorator. Inside the @Module() decorator, you register:

  • Controllers (for handling HTTP requests)

  • Providers (Services) (for business logic)

  • Exports (to make services available to other modules)

A sample Module file for an employee class may look like this:

These are the basic fundamental understandings for NestJs, lets start coding!!!

Last updated