Skip to content

Commit

Permalink
Merge pull request #10737 from mahkassem/Parse-File-Pipe-Fix
Browse files Browse the repository at this point in the history
Parse file pipe fix (multiple files validation)
  • Loading branch information
kamilmysliwiec committed Feb 1, 2023
2 parents 967a136 + 452f194 commit 32b0d9c
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions packages/common/pipes/file/parse-file.pipe.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { isUndefined } from '../../utils/shared.utils';
import { Injectable, Optional } from '../../decorators/core';
import { HttpStatus } from '../../enums';
import { PipeTransform } from '../../interfaces/features/pipe-transform.interface';
import { HttpErrorByCode } from '../../utils/http-error-by-code.util';
import { FileValidator } from './file-validator.interface';
import { ParseFileOptions } from './parse-file-options.interface';
import { isEmpty, isObject } from 'class-validator';

/**
* Defines the built-in ParseFile Pipe. This pipe can be used to validate incoming files
Expand Down Expand Up @@ -39,20 +39,36 @@ export class ParseFilePipe implements PipeTransform<any> {
}

async transform(value: any): Promise<any> {
if (isUndefined(value)) {
if (this.thereAreNoFilesIn(value)) {
if (this.fileIsRequired) {
throw this.exceptionFactory('File is required');
}

return value;
}

if (this.validators.length) {
await this.validate(value);
if (Array.isArray(value)) {
await this.validateFiles(value);
} else {
await this.validate(value);
}
}

return value;
}

private validateFiles(files: any[]): Promise<any[]> {
return Promise.all(files.map(f => this.validate(f)));
}

private thereAreNoFilesIn(value: any): boolean {
if (Array.isArray(value)) {
return value.length === 0;
} else {
return isEmpty(value);
}
}

protected async validate(file: any): Promise<any> {
for (const validator of this.validators) {
await this.validateOrThrow(file, validator);
Expand Down

0 comments on commit 32b0d9c

Please sign in to comment.