Skip to content

Commit

Permalink
refactor: optimize the order of logs and vary in cache keys (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
aui committed May 31, 2024
1 parent ae4dc7e commit cbe32be
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/cool-ravens-shake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@web-widget/shared-cache": patch
---

Optimize the order of logs and vary in cache keys.
15 changes: 10 additions & 5 deletions src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ export class SharedCache implements Cache {
): Promise<void> {
return this.#putWithCustomCacheKey(request, response, options).catch(
(error) => {
this.#logger?.error('Failed to cache response.', {
this.#logger?.error('Cache.put: Failed to cache response.', {
url: request instanceof Request ? request.url : request,
error,
});
Expand Down Expand Up @@ -350,9 +350,10 @@ export class SharedCache implements Cache {
}

if (revalidationResponse.status >= 500) {
this.#logger?.error(`Revalidation failed.`, {
this.#logger?.error(`Cache: Revalidation failed.`, {
url: request.url,
status: revalidationResponse.status,
cacheKey,
});
}

Expand Down Expand Up @@ -392,7 +393,7 @@ async function getCacheItem(
storage: KVStorage,
customCacheKey: string
): Promise<CacheItem> {
const varyKey = `vary:${customCacheKey}`;
const varyKey = getVaryCacheKey(customCacheKey);
const varyFilterOptions: FilterOptions | undefined =
await storage.get(varyKey);
const varyPart = varyFilterOptions
Expand All @@ -408,7 +409,7 @@ async function deleteCacheItem(
storage: KVStorage,
customCacheKey: string
): Promise<boolean> {
const varyKey = `vary:${customCacheKey}`;
const varyKey = getVaryCacheKey(customCacheKey);
const varyFilterOptions: FilterOptions | undefined =
await storage.get(varyKey);
const varyPart = varyFilterOptions
Expand All @@ -431,7 +432,7 @@ async function setCacheItem(
): Promise<void> {
const vary = response.headers.get('vary');
if (vary) {
const varyKey = `vary:${customCacheKey}`;
const varyKey = getVaryCacheKey(customCacheKey);
const varyFilterOptions: FilterOptions =
vary === '*'
? true
Expand All @@ -445,6 +446,10 @@ async function setCacheItem(
}
}

function getVaryCacheKey(customCacheKey: string) {
return `${customCacheKey}:vary`;
}

/**
* @see https://fetch.spec.whatwg.org/#http-scheme
*/
Expand Down

0 comments on commit cbe32be

Please sign in to comment.