Ghost/core/server/utils/cached-image-size-from-url.js
Katharina Irrgang 4e3e1bdfc9 Call getImageSize with timeout (#8044) (#8189)
refs #8041

Calls `getImageSize` with an timeout of 6sec. and adds a default timeout (in case, function is called without optional timeout) of 10sec, to prevent node from using its default timeout of 2minutes 😱
2017-03-20 12:17:27 +00:00

38 lines
1.2 KiB
JavaScript

var Promise = require('bluebird'),
size = require('./image-size-from-url'),
logging = require('../logging'),
getImageSizeFromUrl = size.getImageSizeFromUrl,
imageSizeCache = {};
/**
* Get cached image size from URL
* Always returns {object} imageSizeCache
* @param {string} url
* @returns {Promise<Object>} imageSizeCache
* @description Takes a url and returns image width and height from cache if available.
* If not in cache, `getImageSizeFromUrl` is called and returns the dimensions in a Promise.
*/
function getCachedImageSizeFromUrl(url) {
if (!url || url === undefined || url === null) {
return;
}
// image size is not in cache
if (!imageSizeCache[url]) {
return getImageSizeFromUrl(url, 6000).then(function (res) {
imageSizeCache[url] = res;
return Promise.resolve(imageSizeCache[url]);
}).catch(function (err) {
logging.error(err);
// in case of error we just attach the url
return Promise.resolve(imageSizeCache[url] = url);
});
}
// returns image size from cache
return Promise.resolve(imageSizeCache[url]);
}
module.exports = getCachedImageSizeFromUrl;