This report summarizes data validation and transformation techniques in NestJS, a framework for building Node.js server-side applications.
Importance of Data Validation
Validating data ensures it adheres to predefined rules before reaching the controller layer. This prevents issues like:
Incorrect or Malicious Data: Protects against attacks like SQL injection and unexpected data types.
Errors and Exceptions: Prevents errors caused by invalid data formats.
Benefits
Improved Data Integrity: Guarantees data adheres to defined rules.
Reduced Errors: Prevents issues caused by invalid data.
Cleaner Code: Separates data validation logic from controllers.
Check validation of DTO and input data before controller.
https://github.com/typestack/class-validator

Install packages
yarn add class-validator class-transformerDocument validation
Run in developer mode
yarn start:devAdd Pipe controller
main.ts
import {
NestFactory
}
from '@nestjs/core';
import {
AppModule
}
from './app.module';
import {
ValidationPipe
}
from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();DTO folder
import {
IsNotEmpty
}
from 'class-validator';
export class CreateTaskDto {
@IsNotEmpty() title: string;
@IsNotEmpty() description: string;
}Check Id exists
service
getTaskById(id: string): Task { const found = this.tasks.find((task) => task.id === id); if
(!found) { throw new NotFoundException(`Task with ID "${id}" not found`); } return found;
}Check ID exists when the element was deleted
deleteTask(id: string): void { const found = this.getTaskById(id); this.tasks =
this.tasks.filter((task) => task.id !== found.id); }Check ID exists when the element was updated
updateTaskStatus(id: string, status: TaskStatus): Task { const task = this.getTaskById(id);
task.status = status; return task; }Check Update Status
add update-task-status.dto in dto folder
import {
IsEnum
}
from 'class-validator';
import {
TaskStatus
}
from '../tasks.model';
export class UpdateTaskStatus {
@IsEnum(TaskStatus) status: TaskStatus;
}controller
@Patch('/:id/status') updateTaskStatus(@Param('id') id: string, @Body() updateTaskStatusDto:
UpdateTaskStatusDto,): Task {
const {
status
}
= updateTaskStatusDto;
return this.tasksService.updateTaskStatus(id, status);
}validation for Search
dto
import {
IsEnum, IsOptional, IsString
}
from 'class-validator';
import {
TaskStatus
}
from '../tasks.model';
export class GetTasksFilterDto {
@IsOptional() @IsEnum(TaskStatus) status?: TaskStatus;
@IsOptional() @IsString() search?: string;
}