Skip to content

Commit bdd9397

Browse files
committed
refactor(common): parse file pipe
add async validation feature
1 parent 2ad8648 commit bdd9397

3 files changed

Lines changed: 16 additions & 10 deletions

File tree

packages/common/pipes/file/file-validator.interface.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export abstract class FileValidator<TValidationOptions = Record<string, any>> {
88
* Indicates if this file should be considered valid, according to the options passed in the constructor.
99
* @param file the file from the request object
1010
*/
11-
abstract isValid(file?: any): boolean;
11+
abstract isValid(file?: any): boolean | Promise<boolean>;
1212

1313
/**
1414
* Builds an error message in case the validation fails.

packages/common/pipes/file/parse-file.pipe.ts

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { HttpErrorByCode } from '../../utils/http-error-by-code.util';
44
import { PipeTransform } from '../../interfaces/features/pipe-transform.interface';
55
import { ParseFileOptions } from './parse-file-options.interface';
66
import { FileValidator } from './file-validator.interface';
7+
import { throws } from 'assert';
78

89
/**
910
* Defines the built-in ParseFile Pipe. This pipe can be used to validate incoming files
@@ -36,21 +37,26 @@ export class ParseFilePipe implements PipeTransform<any> {
3637

3738
async transform(value: any): Promise<any> {
3839
if (this.validators.length) {
39-
this.validate(value);
40+
await this.validate(value);
4041
}
4142
return value;
4243
}
4344

44-
protected validate(file: any): any {
45-
const failingValidator = this.validators.find(
46-
validator => !validator.isValid(file),
47-
);
45+
protected async validate(file: any): Promise<any> {
46+
for (const validator of this.validators) {
47+
await this.validateOrThrow(file, validator);
48+
}
49+
50+
return file;
51+
}
52+
53+
private async validateOrThrow(file: any, validator: FileValidator) {
54+
const isValid = await validator.isValid(file);
4855

49-
if (failingValidator) {
50-
const errorMessage = failingValidator.buildErrorMessage(file);
56+
if (!isValid) {
57+
const errorMessage = validator.buildErrorMessage(file);
5158
throw this.exceptionFactory(errorMessage);
5259
}
53-
return file;
5460
}
5561

5662
/**

packages/common/test/pipes/file/parse-file.pipe.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ describe('ParseFilePipe', () => {
7878
});
7979
});
8080

81-
describe('when some the validator invalidates the file', () => {
81+
describe('when some validator invalidates the file', () => {
8282
describe('and the pipe has the default error', () => {
8383
beforeEach(() => {
8484
parseFilePipe = new ParseFilePipe({

0 commit comments

Comments
 (0)