Skip to content

Commit

Permalink
Refactored handle-image-sizes middleware to async-await
Browse files Browse the repository at this point in the history
- this is much easier to read and reason about
  • Loading branch information
daniellockyer committed Mar 12, 2024
1 parent bfb9bfe commit cc72313
Showing 1 changed file with 25 additions and 25 deletions.
50 changes: 25 additions & 25 deletions ghost/core/core/frontend/web/middleware/handle-image-sizes.js
Expand Up @@ -110,35 +110,35 @@ module.exports = function handleImageSizes(req, res, next) {
return redirectToOriginal();
}

storageInstance.exists(req.url).then((exists) => {
storageInstance.exists(req.url).then(async (exists) => {
if (exists) {
return;
}

return imageSize.getOriginalImagePath(imagePath)
.then((storagePath) => {
return storageInstance.read({path: storagePath});
})
.then((originalImageBuffer) => {
if (originalImageBuffer.length <= 0) {
throw new NoContentError();
}
return imageTransform.resizeFromBuffer(originalImageBuffer, {withoutEnlargement: requestUrlFileExtension !== '.svg', ...imageDimensionConfig, format});
})
.then((resizedImageBuffer) => {
return storageInstance.saveRaw(resizedImageBuffer, req.url);
});
}).then(() => {
if (format) {
// File extension won't match the new format, so we need to update the Content-Type header manually here
// Express JS still uses an out of date mime package, which doesn't support avif
res.type(format === 'avif' ? 'image/avif' : format);
}
next();
}).catch(function (err) {
if (err.code === 'SHARP_INSTALLATION' || err.code === 'IMAGE_PROCESSING' || err.errorType === 'NoContentError') {
return redirectToOriginal();
try {
const storagePath = await imageSize.getOriginalImagePath(imagePath);
const originalImageBuffer = await storageInstance.read({path: storagePath});

if (originalImageBuffer.length <= 0) {
throw new NoContentError();
}

const resizedImageBuffer = await imageTransform.resizeFromBuffer(originalImageBuffer, {withoutEnlargement: requestUrlFileExtension !== '.svg', ...imageDimensionConfig, format});

await storageInstance.saveRaw(resizedImageBuffer, req.url);

if (format) {
// File extension won't match the new format, so we need to update the Content-Type header manually here
// Express JS still uses an out of date mime package, which doesn't support avif
res.type(format === 'avif' ? 'image/avif' : format);
}

next();
} catch (err) {
if (err.code === 'SHARP_INSTALLATION' || err.code === 'IMAGE_PROCESSING' || err.errorType === 'NoContentError') {
return redirectToOriginal();
}
next(err);
}
next(err);
});
};

0 comments on commit cc72313

Please sign in to comment.