From b26144609a76c3da452e2dd9846ba0805cc15a5c Mon Sep 17 00:00:00 2001 From: colin3191 <319151881@qq.com> Date: Thu, 31 Aug 2023 18:46:34 +0800 Subject: [PATCH] feat: cache request itself --- src/dataurl.ts | 48 ++++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) 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] }