Skip to content

Instantly share code, notes, and snippets.

View Vatsalya-singhi's full-sized avatar

Vatsalya Singhi Vatsalya-singhi

View GitHub Profile
// Users Service (Provides Business Logic)
import { Injectable } from '@nestjs/common';
// injectables include wide range of configurations such as when and how to initialise the provider
@Injectable()
export class UsersService {
private users = ['Alice', 'Bob', 'Charlie'];
findAll(): string[] {
return this.users;
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
@Module({
controllers: [UsersController], // Registers the controller
providers: [UsersService], // Registers the service
exports: [UsersService], // Allows other modules to use UsersService
imports: []
})
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Pass control to the next handler
}
}
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { LoggerMiddleware } from './logger.middleware';
@Module({
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule implements NestModule {
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Response } from 'express';
@Catch(HttpException) // Catches only HTTP-related exceptions
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
const message = exception.getResponse();
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './http-exception.filter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpExceptionFilter()); // Apply globally
await app.listen(3000);
}
import { Controller, Get, UseFilters, HttpException, HttpStatus } from '@nestjs/common';
import { HttpExceptionFilter } from './http-exception.filter';
@Controller('users')
@UseFilters(HttpExceptionFilter) // Apply to all methods in this controller
export class UsersController {
@Get()
findAll() {
throw new HttpException('Users not found', HttpStatus.NOT_FOUND);
}
@Get()
@UseFilters(HttpExceptionFilter) // Apply to only this method
findAll() {
throw new HttpException('Users not found', HttpStatus.NOT_FOUND);
}
import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return { message: `Fetching user with ID ${id}` };
}
}
// convert strings to uppercase
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
@Injectable()
export class UppercasePipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
return typeof value === 'string' ? value.toUpperCase() : value;
}
}