Skip to content

Commit 0912528

Browse files
committed
feat(common): add required file validation
ensure ParseFilePipe throws an error when a file is required but was not passed
1 parent 657428e commit 0912528

3 files changed

Lines changed: 29 additions & 1 deletion

File tree

packages/common/pipes/file/parse-file-options.interface.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,9 @@ export interface ParseFileOptions {
55
validators?: FileValidator[];
66
errorHttpStatusCode?: ErrorHttpStatusCode;
77
exceptionFactory?: (error: string) => any;
8+
9+
/**
10+
* Defines if file parameter is optional. Default is false.
11+
*/
812
fileIsOptional?: boolean;
913
}

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,24 +20,31 @@ import { ParseFileOptions } from './parse-file-options.interface';
2020
export class ParseFilePipe implements PipeTransform<any> {
2121
protected exceptionFactory: (error: string) => any;
2222
private readonly validators: FileValidator[];
23+
private readonly fileIsOptional: boolean;
2324

2425
constructor(@Optional() options: ParseFileOptions = {}) {
2526
const {
2627
exceptionFactory,
2728
errorHttpStatusCode = HttpStatus.BAD_REQUEST,
2829
validators = [],
30+
fileIsOptional,
2931
} = options;
3032

3133
this.exceptionFactory =
3234
exceptionFactory ||
3335
(error => new HttpErrorByCode[errorHttpStatusCode](error));
3436

3537
this.validators = validators;
38+
this.fileIsOptional = fileIsOptional ?? false;
3639
}
3740

3841
async transform(value: any): Promise<any> {
3942
if (isUndefined(value)) {
40-
return value;
43+
if (this.fileIsOptional) {
44+
return value;
45+
}
46+
47+
throw this.exceptionFactory('File is required');
4148
}
4249

4350
if (this.validators.length) {

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,5 +133,22 @@ describe('ParseFilePipe', () => {
133133
);
134134
});
135135
});
136+
137+
describe('when file is not optional', () => {
138+
beforeEach(() => {
139+
parseFilePipe = new ParseFilePipe({
140+
validators: [new AlwaysInvalidValidator({})],
141+
fileIsOptional: false,
142+
});
143+
});
144+
145+
it('should throw an error if no file is provided', async () => {
146+
const requestFile = undefined;
147+
148+
await expect(parseFilePipe.transform(requestFile)).to.be.rejectedWith(
149+
BadRequestException,
150+
);
151+
});
152+
});
136153
});
137154
});

0 commit comments

Comments
 (0)