avatarMertcan Arguç

Summarize

NestJS: Unwrapping the Magic with Top 10 Utility Classes

https://nestjs.com/

Ever felt like coding needs some magic? NestJS is waving its wand! Here are ten of its most enchanting tools ready to sprinkle some magic on your code.

1. Graceful Oopsies with HttpExceptionFilter

Errors can be drama queens, always seeking attention. But HttpExceptionFilter ensures they make a classy appearance, not a clumsy entrance.

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

@Catch(HttpException)
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();
      
    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: ctx.getRequest().url,
    });
  }
}
// "Drama alert! But I've got the spotlight controls."

2. Pipes: The App’s VIP Bouncers

Pipes are the guardians at the gate, ensuring that the data walks the talk.

import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common';

@Controller('items')
export class ItemsController {
  @Get(':id')
  findOne(@Param('id', new ParseIntPipe()) id: number) {
    return `Item ${id}`;
  }
}
// "Data, please behave, or you're out!"

3. Interceptors: The Data Whisperers

Interceptors tweak and twist, making sure data’s journey is smooth and styled.

import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { TransformInterceptor } from './transform.interceptor';

@Controller('data')
@UseInterceptors(TransformInterceptor)
export class DataController {
  @Get()
  fetchData() {
    return { message: 'Data fetched successfully!' };
  }
}
// "A sprinkle of style and voila! Perfecto!"

4. Guards: The Digital Doorkeepers

They stand tall, ensuring only the worthy can pass.

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return request.user != null;
  }
}
// "Stop! Password or invitation, please."

5. Decorators: Swift Shortcuts

Decorators are like those quick access passes, always ready to serve.

import { Controller, Get } from '@nestjs/common';

@Controller('profile')
export class ProfileController {
  @Get()
  getProfile(@Req() request) {
    return request.user;
  }
}
// "Quick peek, and here's your profile!"

6. Modules: The Organized Librarians

Every piece of code finds its right place, all thanks to Modules.

import { Module } from '@nestjs/common';
import { ItemsController } from './items.controller';
import { ItemsService } from './items.service';

@Module({
  controllers: [ItemsController],
  providers: [ItemsService],
})
export class ItemsModule {}
// "Every code in its right place, please!"

7. Schedulers: The Clockwork Companions

Schedulers, always ticking, ensuring tasks run just in time.

import { Injectable, Logger } from '@nestjs/common';
import { Interval } from '@nestjs/schedule';

@Injectable()
export class TasksService {
  private readonly logger = new Logger(TasksService.name);
  @Interval(10000)
  handleInterval() {
    this.logger.debug('Called every 10 seconds');
  }
}
// "And... action! Right on time."

8. Swagger: The Grand Stage Manager

Swagger sets the stage, presenting your app’s capabilities with flair.

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const options = new DocumentBuilder()
    .setTitle('API Documentation')
    .setDescription('My API description')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document);
  await app.listen(3000);
}
// "Behold the grandeur of this app!"

9. ConfigModule: The Maestro of Tuning

When you want your app to hum a different tune based on where it’s performing, ConfigModule steps up as the maestro, finely tuning your app's settings to perfection.

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // this makes the config available everywhere
      envFilePath: '.env',
    }),
  ],
})
export class AppModule {}
// "Shhh... Adjusting the strings so the music plays just right!"

10. Microservices: The Symphony Conductors

In an orchestra of distributed services, you need a skilled conductor. Microservices in NestJS ensure each section communicates in harmony, delivering a melodious performance.

import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.createMicroservice(AppModule, {
    transport: Transport.TCP,
    options: {
      host: '127.0.0.1',
      port: 8877,
    },
  });
  app.listen(() => console.log('Microservice is orchestrating beautifully!'));
}
// "Strings, wind, percussion... All in harmony!"

There we go, a whimsical tour through NestJS’s star-studded toolkit. With these dazzling utility classes, you’re all set to craft a masterpiece. Shine on, dear coder, shine on! 🌟🎵

If you enjoyed this article, consider trying out the AI service I recommend. It provides the same performance and functions to ChatGPT Plus(GPT-4) but more cost-effective, at just $6/month (Special offer for $1/month). Click here to try ZAI.chat.

Programming
Technology
Software Development
Web Development
JavaScript
Recommended from ReadMedium