diff --git a/src/dataurl.ts b/src/dataurl.ts index 13bc8b43..092f61b1 100644 --- a/src/dataurl.ts +++ b/src/dataurl.ts @@ -37,7 +37,7 @@ export async function fetchAsDataURL( }) } -const cache: { [url: string]: string } = {} +const cache: { [url: string]: Promise } = {} function getCacheKey( url: string, @@ -58,27 +58,11 @@ function getCacheKey( return contentType ? `[${contentType}]${key}` : key } -export async function resourceToDataURL( +async function fetchAndMakeDataURL( resourceUrl: string, contentType: string | undefined, options: Options, ) { - const cacheKey = getCacheKey( - resourceUrl, - contentType, - options.includeQueryParams, - ) - - if (cache[cacheKey] != null) { - return cache[cacheKey] - } - - // ref: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache - if (options.cacheBust) { - // eslint-disable-next-line no-param-reassign - resourceUrl += (/\?/.test(resourceUrl) ? '&' : '?') + new Date().getTime() - } - let dataURL: string try { const content = await fetchAsDataURL( @@ -93,6 +77,7 @@ export async function resourceToDataURL( }, ) dataURL = makeDataUrl(content, contentType!) + return dataURL } catch (error) { dataURL = options.imagePlaceholder || '' @@ -104,8 +89,31 @@ export async function resourceToDataURL( if (msg) { console.warn(msg) } + return dataURL + } +} + +export async function resourceToDataURL( + resourceUrl: string, + contentType: string | undefined, + options: Options, +) { + const cacheKey = getCacheKey( + resourceUrl, + contentType, + options.includeQueryParams, + ) + + if (cache[cacheKey] != null) { + return cache[cacheKey] + } + + // ref: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache + if (options.cacheBust) { + // eslint-disable-next-line no-param-reassign + resourceUrl += (/\?/.test(resourceUrl) ? '&' : '?') + new Date().getTime() } - cache[cacheKey] = dataURL - return dataURL + cache[cacheKey] = fetchAndMakeDataURL(resourceUrl, contentType, options) + return cache[cacheKey] }