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

NestJS: Data Validation and Transformation

Install packages

bash
yarn add class-validator class-transformer

Document validation

Run in developer mode

bash
yarn start:dev

Add Pipe controller

main.ts

typescript
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

typescript
import {
  IsNotEmpty
}
from 'class-validator';
export class CreateTaskDto {
  @IsNotEmpty() title: string;
  @IsNotEmpty() description: string;
}

Check Id exists

service

typescript
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

typescript
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

typescript
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

typescript
import {
  IsEnum
}
from 'class-validator';
import {
  TaskStatus
}
from '../tasks.model';
export class UpdateTaskStatus {
  @IsEnum(TaskStatus) status: TaskStatus;
}

controller

typescript
@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

typescript
import {
  IsEnum, IsOptional, IsString
}
from 'class-validator';
import {
  TaskStatus
}
from '../tasks.model';
export class GetTasksFilterDto {
  @IsOptional() @IsEnum(TaskStatus) status?: TaskStatus;
  @IsOptional() @IsString() search?: string;
}