Skip to content

Instantly share code, notes, and snippets.

View Vatsalya-singhi's full-sized avatar

Vatsalya Singhi Vatsalya-singhi

View GitHub Profile
import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
import { CreateUserDto } from './create-user.dto';
@Controller('users')
export class UsersController {
@Post()
@UsePipes(new ValidationPipe()) // Apply validation
create(@Body() createUserDto: CreateUserDto) {
return { message: 'User created', data: createUserDto };
}
import { IsString, IsInt, MinLength, Min } from 'class-validator';
export class CreateUserDto {
@IsString()
@MinLength(3)
name: string;
@IsInt()
@Min(18)
age: number;
// Custom Pipe used in a Controller
import { Controller, Post, Body } from '@nestjs/common';
import { UppercasePipe } from './uppercase.pipe';
@Controller('users')
export class UsersController {
@Post()
create(@Body('name', new UppercasePipe()) name: string) {
return { message: 'User created', name };
}
// 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;
}
}
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}` };
}
}
@Get()
@UseFilters(HttpExceptionFilter) // Apply to only this method
findAll() {
throw new HttpException('Users not found', HttpStatus.NOT_FOUND);
}
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);
}
// 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 { 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();
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 {