move try catch to image manipulation

This commit is contained in:
Marc-Roig 2022-08-03 20:39:44 +02:00
parent ff932b1cb3
commit 5b0bcab7b1
2 changed files with 39 additions and 33 deletions

View File

@ -4,6 +4,7 @@
*/
const fs = require('fs');
const { join } = require('path');
const { ApplicationError } = require('@strapi/utils').errors;
const sharp = require('sharp');
const { getService } = require('../utils');
@ -45,7 +46,12 @@ const THUMBNAIL_RESIZE_OPTIONS = {
const resizeFileTo = async (file, options, { name, hash }) => {
const filePath = join(file.tmpWorkingDirectory, hash);
try {
await writeStreamToFile(file.getStream().pipe(sharp().resize(options)), filePath);
} catch (err) {
throw new ApplicationError('File is not a valid image');
}
const newFile = {
name,
@ -101,7 +107,13 @@ const optimize = async file => {
transformer.rotate();
}
const filePath = join(file.tmpWorkingDirectory, `optimized-${file.hash}`);
try {
await writeStreamToFile(file.getStream().pipe(transformer), filePath);
} catch {
throw new ApplicationError('File is not a valid image');
}
newFile.getStream = () => fs.createReadStream(filePath);
}

View File

@ -18,7 +18,7 @@ const {
contentTypes: contentTypesUtils,
webhook: webhookUtils,
} = require('@strapi/utils');
const { NotFoundError, ForbiddenError } = require('@strapi/utils').errors;
const { NotFoundError } = require('@strapi/utils').errors;
const { MEDIA_UPDATE, MEDIA_CREATE, MEDIA_DELETE } = webhookUtils.webhookEvents;
@ -126,7 +126,6 @@ module.exports = ({ strapi }) => ({
if (!(await isOptimizableImage(currentFile))) {
return currentFile;
}
return optimize(currentFile);
},
@ -144,7 +143,6 @@ module.exports = ({ strapi }) => ({
const doUpload = async (file, fileInfo) => {
const fileData = await this.enhanceFile(file, fileInfo, metas);
return this.uploadFileAndPersist(fileData, { user });
};
@ -173,7 +171,6 @@ module.exports = ({ strapi }) => ({
isOptimizableImage,
} = getService('image-manipulation');
try {
// Store width and height of the original image
const { width, height } = await getDimensions(fileData);
@ -208,9 +205,6 @@ module.exports = ({ strapi }) => ({
}
}
}
} catch (err) {
throw new ForbiddenError('File is not a valid image');
}
},
/**