I am trying to check that a list of files are all images using functional programming.
Some actions I go through are asynchronous, so I have to wait for them to completely finish before passing to a new one.
const filteredFiles = ['favicon.ico', 'site.webmanifest', 'browserconfig.xml'];
const fileBuffers = await Promise.all(
directory.files
.filter(file => !filteredFiles.includes(file.path))
// get a buffer containing the image file
.map(async file => await file.buffer())
)
const everyFileIsImage = (await Promise.all(
// check that this buffer has correct mime type
fileBuffers.map(async buffer => await this.bufferIsImageFile(buffer))
)).every(isImage => isImage);
if (!everyFileIsImage) {
throw new BadRequestException(`All files except ${filteredFiles} must be images`);
}
Here is the bufferIsImageFile
method which is using the file-type
library
private async bufferIsImageFile(buffer) {
const type = await FileType.fromBuffer(buffer);
return type !== undefined && type.mime.startsWith('image/');
}
I am not all satisfied by the piece of code. But I'm also not sure on how it could be improved.
What I'd like the most would be to avoid using those Promise.all
, but is it even possible?
Maybe should I use a for
loop instead?
bufferIsImageFile
method. \$\endgroup\$