This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: [] | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Get() | |
@UseFilters(HttpExceptionFilter) // Apply to only this method | |
findAll() { | |
throw new HttpException('Users not found', HttpStatus.NOT_FOUND); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}` }; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |