Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse file pipe fix (multiple files validation) #10737

Merged
merged 2 commits into from
Feb 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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