Skip to content

Commit

Permalink
fix: cache response body instead of full response (#185)
Browse files Browse the repository at this point in the history
Hi @simar0at I think I found an easy fix - could you check if this works
for you (and the other setups) as well - thank you! :)
  • Loading branch information
simar0at authored Oct 22, 2024
2 parents 4cdedfa + 0ca2dba commit 3d06291
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions composables/use-api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function basicSecurityWorker(securityData: userPass | null): RequestParams | und
return undefined;
}

const cache: Map<string, Record<string, Response>> = new Map<string, Record<string, Response>>();
const cache: Map<string, Record<string, unknown>> = new Map<string, Record<string, unknown>>();

async function fetchWithETag(
input: globalThis.Request | URL | string,
Expand All @@ -41,13 +41,15 @@ async function fetchWithETag(

if (response.status === 304) {
if (cachedETag && Object.keys(cachedETag).length === 1) {
const response = Object.values(cachedETag)[0];
if (response) return response.clone();
const body = Object.values(cachedETag)[0];
if (body) return new Response(JSON.stringify(body), { status: 200 });
}
throw new Error(`Cache error!`);
} else if (response.ok) {
if (currentETag) {
cache.set(url, { [currentETag]: response.clone() });
// response body can't be typed at this point
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
cache.set(url, { [currentETag]: await response.clone().json() });
}
return response;
} else {
Expand Down

0 comments on commit 3d06291

Please sign in to comment.