#How to create validator for file uploads

6 messages · Page 1 of 1 (latest)

amber surge
#

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:

  1. There is code duplicacy when adding same logic to other endpoints.
  2. 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

manic island
# amber surge Currently when validating file uploads in any endpoint I'm using the following s...

instead of adding a pipe you can apply a default to the multer module it self, pointed out by the docs
options can be found in the multer docs

GitHub

Node.js middleware for handling multipart/form-data. - expressjs/multer

#

alternatively, you can use the multer storage option and change the storage handler, like a third party one
allowing you for more option controlls

amber surge
manic island
amber surge
#

Ok understood