Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: cache request itself #430

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
})
}

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

function getCacheKey(
url: string,
Expand All @@ -58,27 +58,11 @@
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 @@
},
)
dataURL = makeDataUrl(content, contentType!)
return dataURL
} catch (error) {
dataURL = options.imagePlaceholder || ''

Expand All @@ -104,8 +89,31 @@
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]
}
Loading