Skip to content
Merged
Show file tree
Hide file tree
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
6 changes: 3 additions & 3 deletions packages/cacheable-request/test/cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,10 +350,10 @@ test("return with protocol", async () => {

test("hostname over host", async () => {
const options = {
host: "mockhttp.org",
hostname: "cacheable.org",
host: "example.org",
hostname: "mockhttp.org",
};
const expected = "GET:http://cacheable.org";
const expected = "GET:http://mockhttp.org";
const expectKey = `cacheable-request:${expected}`;
const actualKey = await testCacheKeyReturn(options);
expect(actualKey).toBe(expectKey);
Expand Down
28 changes: 25 additions & 3 deletions packages/net/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,38 @@ export async function fetch(
cache: "no-cache",
};

return options.cache.getOrSet(url, async () => {
// Create a cache key that includes the method
const cacheKey = `${options.method || "GET"}:${url}`;

const cachedData = await options.cache.getOrSet(cacheKey, async () => {
// Perform the fetch operation
const response = await undiciFetch(url, fetchOptions);
/* c8 ignore next 3 */
if (!response.ok) {
throw new Error(`Fetch failed with status ${response.status}`);
}

return response;
}) as Promise<UndiciResponse>;
// Convert response to cacheable format
const body = await response.text();
return {
body,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
};
});

// Reconstruct Response object from cached data
/* c8 ignore next 3 */
if (!cachedData) {
throw new Error("Failed to get or set cache data");
}

return new Response(cachedData.body, {
status: cachedData.status,
statusText: cachedData.statusText,
headers: cachedData.headers,
}) as UndiciResponse;
}

export type Response = UndiciResponse;
Expand Down
8 changes: 8 additions & 0 deletions packages/net/test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,15 @@ describe("Fetch", () => {
cache,
};
const response = await fetch(url, options);
const response2 = await fetch(url, options);
expect(response).toBeDefined();
expect(response2).toBeDefined();
expect(cache.stats).toBeDefined();
expect(cache.stats.hits).toBe(1);
// Verify that both responses have the same text content
const text1 = await response.text();
const text2 = await response2.text();
expect(text1).toEqual(text2);
},
testTimeout,
);
Expand Down