Skip to content

Commit

Permalink
feat: cache request itself
Browse files Browse the repository at this point in the history
  • Loading branch information
Colin3191 committed Aug 31, 2023
1 parent d913a2e commit b261446
Showing 1 changed file with 28 additions and 20 deletions.
48 changes: 28 additions & 20 deletions src/dataurl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export async function fetchAsDataURL<T>(
})
}

const cache: { [url: string]: string } = {}
const cache: { [url: string]: Promise<string> } = {}

function getCacheKey(
url: string,
Expand All @@ -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(
Expand All @@ -93,6 +77,7 @@ export async function resourceToDataURL(
},
)
dataURL = makeDataUrl(content, contentType!)
return dataURL
} catch (error) {
dataURL = options.imagePlaceholder || ''

Expand All @@ -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,

Check warning on line 99 in src/dataurl.ts

View check run for this annotation

Codecov / codecov/patch

src/dataurl.ts#L99

Added line #L99 was not covered by tests
) {
const cacheKey = getCacheKey(
resourceUrl,
contentType,
options.includeQueryParams,
)

Check warning on line 105 in src/dataurl.ts

View check run for this annotation

Codecov / codecov/patch

src/dataurl.ts#L105

Added line #L105 was not covered by tests

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]
}

0 comments on commit b261446

Please sign in to comment.