Currently when validating file uploads in any endpoint I'm using the following snippet:
async addPDF(
@UploadedFile(
new ParseFilePipeBuilder()
.addMaxSizeValidator({
maxSize: CONSTANTS.FILE.MAX_SIZE,
message: CONSTANTS.FILE.MAX_SIZE_ERROR_MESSAGE,
})
.addFileTypeValidator({
fileType: Commons.generateRegexFromArrayForOr(CONSTANTS.FILE.ALLOWED_FILE_TYPES),
})
.build()
) file): Promise<any> {
return this.pdfService.createPDF({
request: {
fileContent: file,
},
});
}
Using this approach, I'm facing two problems:
- There is code duplicacy when adding same logic to other endpoints.
- The file type validator is validating based on extension.
My aim is to create a custom validator which performs type validation based on magic number and can be reused in other endpoints. It should take the size and allowed types as inputs.
Can anyone please help me how I can create one custom validator for this purpose and use it in the endpoints? Any documentation or sample code will be helpful.
Thanks