NestJS Framework

NestJS #

NestJS is a powerful and extensible web application framework for Node.js, built with TypeScript and inspired by Angular. It provides a modular and structured approach to developing server-side applications, emphasizing scalability, maintainability, and ease of testing. Here’s a basic overview of NestJS:

Installation: #

Install NestJS using the following command:

npm install -g @nestjs/cli

Creating a Project: #

Generate a new NestJS project with the CLI:

nest new my-project

Hello World Example: #

Create a simple controller with a “Hello, NestJS!” endpoint:

// src/app.controller.ts
import { Controller, Get } from '@nestjs/common';

@Controller()
export class AppController {
    @Get()
    getHello(): string {
        return 'Hello, NestJS!';
    }
}

Modules and Dependency Injection: #

NestJS uses modules to organize the application into cohesive units. Dependency injection is fundamental to NestJS:

// src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';

@Module({
    controllers: [AppController],
})
export class AppModule {}

Routing and Decorators: #

Use decorators to define routes and HTTP methods within controllers:

// src/app.controller.ts
import { Controller, Get, Post } from '@nestjs/common';

@Controller('example')
export class AppController {
    @Get()
    getHello(): string {
        return 'Hello, NestJS!';
    }

    @Post()
    postHello(): string {
        return 'Post request received!';
    }
}

Middleware: #

Implement middleware functions for common tasks, such as logging:

// src/logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
    use(req: any, res: any, next: () => void) {
        console.log('Request received...');
        next();
    }
}
// src/app.module.ts
import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { LoggerMiddleware } from './logger.middleware';

@Module({
    controllers: [AppController],
})
export class AppModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
        consumer.apply(LoggerMiddleware).forRoutes('example');
    }
}

Services and Dependency Injection: #

Define services to encapsulate business logic and use dependency injection to inject them into controllers:

// src/app.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
    getHello(): string {
        return 'Hello, NestJS!';
    }
}
// src/app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
    constructor(private readonly appService: AppService) {}

    @Get()
    getHello(): string {
        return this.appService.getHello();
    }
}

Exception Filters: #

Handle exceptions with custom filters:

// src/http-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const status = exception.getStatus();

        response.status(status).json({
            statusCode: status,
            message: 'Custom exception message',
        });
    }
}
// src/app.controller.ts
import { Controller, Get, UseFilters } from '@nestjs/common';
import { HttpExceptionFilter } from './http-exception.filter';

@Controller()
export class AppController {
    @Get()
    @UseFilters(HttpExceptionFilter)
    getHello() {
        throw new HttpException('Not Found', HttpStatus.NOT_FOUND);
    }
}

Data Validation: #

Use validation pipes for automatic data validation:

// src/app.controller.ts
import { Controller, Post, Body } from '@nestjs/common';

@Controller('cats')
export class CatsController {
    @Post()
    create(@Body() createCatDto: CreateCatDto) {
        return 'This action adds a new cat';
    }
}

Swagger Integration: #

Integrate Swagger for automatic API documentation:

// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
    const app = await NestFactory.create(AppModule);

    const config = new DocumentBuilder()
        .setTitle('NestJS Example')
        .setDescription('The NestJS API description')
        .setVersion('1.0')
        .build();

    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('api', app, document);

    await app.listen(3000);
}
bootstrap();
NestJS offers a robust and structured framework for building scalable and maintainable server-side applications in Node.js. With its focus on TypeScript, modular architecture, dependency injection, and a set of powerful features, NestJS is well-suited for building modern and efficient web applications and APIs.

Happy coding!
Published on