Performance: File validation pipe
This affects the server response time and user experience by validating files before processing, impacting input responsiveness and backend load.
import { PipeTransform, Injectable, BadRequestException, ArgumentMetadata } from '@nestjs/common'; @Injectable() export class FileValidationPipe implements PipeTransform<Express.Multer.File> { async transform(value: Express.Multer.File, metadata: ArgumentMetadata) { if (!value) { throw new BadRequestException('No file provided'); } // Use async checks or offload heavy validation if (value.size > 10 * 1024 * 1024) { throw new BadRequestException('File too large'); } if (!['image/png', 'image/jpeg'].includes(value.mimetype)) { throw new BadRequestException('Invalid file type'); } return value; } }
import { PipeTransform, Injectable, BadRequestException, ArgumentMetadata } from '@nestjs/common'; @Injectable() export class FileValidationPipe implements PipeTransform<Express.Multer.File> { transform(value: Express.Multer.File, metadata: ArgumentMetadata) { if (!value) { throw new BadRequestException('No file provided'); } if (value.size > 10 * 1024 * 1024) { // 10MB limit throw new BadRequestException('File too large'); } if (!['image/png', 'image/jpeg'].includes(value.mimetype)) { throw new BadRequestException('Invalid file type'); } return value; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous file validation in pipe | 0 (server-side) | 0 | 0 | [X] Bad |
| Asynchronous or lightweight validation in pipe | 0 (server-side) | 0 | 0 | [OK] Good |
FileValidationPipe in NestJS?FileValidationPipe specifically checks uploaded files for correct type, size, and presence to prevent bad data.@UsePipes() decorator.FileValidationPipe is a pipe, so it must be passed inside @UsePipes() to validate the uploaded file.export class FileValidationPipe implements PipeTransform {
transform(file: Express.Multer.File) {
if (!file) throw new BadRequestException('File is required');
if (file.size > 1_000_000) throw new BadRequestException('File too large');
return file;
}
}file.size is greater than 1,000,000 bytes (1MB).BadRequestException('File too large'), stopping the request.export class FileValidationPipe implements PipeTransform {
transform(file: Express.Multer.File) {
if (!file) throw new BadRequestException('File is required');
if (file.mimetype !== 'image/png' || file.mimetype !== 'image/jpeg') {
throw new BadRequestException('Invalid file type');
}
return file;
}
}|| (OR) between two checks: file.mimetype !== 'image/png' OR file.mimetype !== 'image/jpeg'.if (!file) throw, then if (file.mimetype !== 'application/pdf') throw 'Only PDFs allowed'. Uses !== to reject non-PDFs.if (file.size >= 2_000_000) throw 'File too large'. Uses >= to reject 2MB or larger.&& accepts non-PDF if small; D's > accepts exactly 2MB.Pass the test and this pattern moves unknown