Young Al Capone
Young Al Capone

Reputation: 399

How to validate request excel data on NestJs?

I'm trying to validate datatypes and constraints from an excel file (file passed from body request) but I can't do it!. I was reading about class-validator but I think it is not work for me because I'm not receiving a json data just an excel file passed from request body as a file. I've coded a service where I put the logic for read the entire file and add to a array (as my data dto). There is some way to validate every field in this point and return if a problem has been detected? Thanks :)

File Controller:

@Controller('file-parser')
export class FileParserController {
  constructor(private readonly fileParserService: FileParserService) {}

  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  UploadExcelFile(@UploadedFile() file: Express.Multer.File) {
    return this.fileParserService.processFile(file);
  }
}

File Service:

processFile(file: Express.Multer.File): void {
    const workBook: XLSX.WorkBook = XLSX.read(file.buffer, {
      type: 'buffer',
      cellDates: true,
      cellNF: false,
    });
    const sheetName = workBook?.SheetNames[0]; // asigne first sheet name of file
    const sheet: XLSX.WorkSheet = workBook.Sheets[sheetName]; // entire sheet information asigned to sheet variable
    
    const jsonData: StudentDTO[] = XLSX.utils.sheet_to_json(sheet, {
      dateNF: 'YYYY-MM-DD',
    });
    // Add fields validation here
    console.log(jsonData);
  }

Student DTO:

import { IsNotEmpty, IsNumber, IsOptional, IsString, MaxLength } from 'class-validator';
export class StudentDTO {
  id: number;
  @IsString()
  @IsNotEmpty()
  @MaxLength(25)
  studentCode: string;
  @IsString()
  @IsNotEmpty()
  @MaxLength(50)
  studentName: string;
  @IsString()
  @IsNotEmpty()
  @MaxLength(50)
  studentLastname: string;
}

Upvotes: 0

Views: 2734

Answers (1)

TPoschel
TPoschel

Reputation: 3872

I solved a similar problem by using a combination of class-transformer and class-validator. Once you have your raw jsonData I called class-transformer.plainToClass() and then class-validator.validate(). Here is roughly what you would need:

const students: StudentDTO[] = plainToClass(
   StudentDTO[],
   jsonData,
   { excludeExtraneousValues: false},
);

const validatorOptions: ValidatorOptions = {
   whitelist: true, // strips all properties that don't have any decorators
   skipMissingProperties: false,
   forbidUnknownValues: true,
   validationError: {
      target: false,
      value: false,
   },
};
const errors = await validate(students, validatorOptions);

Upvotes: 4

Related Questions