Skip to content

Commit

Permalink
Merge pull request #105 from preactjs/feat/patched-fetch-response
Browse files Browse the repository at this point in the history
feat: Return proper `Response` from patched `fetch` during prerender
  • Loading branch information
rschristian committed Feb 19, 2024
2 parents 44d6cb9 + a551c03 commit 070c20c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
3 changes: 2 additions & 1 deletion demo/src/components/LocalFetch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ const cache = new Map();

async function load(url: string) {
const res = await fetch(url);
return await res.text();
if (res.ok) return await res.text();
throw new Error(`Failed to fetch ${url}!`);
}

function useFetch(url: string) {
Expand Down
23 changes: 14 additions & 9 deletions src/prerender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,15 +169,20 @@ export function PrerenderPlugin({
// @ts-ignore
globalThis.fetch = async (url: string, opts: RequestInit | undefined) => {
if (/^\//.test(url)) {
const text = () =>
fs.readFile(
`${path.join(
viteConfig.root,
viteConfig.build.outDir,
)}/${url.replace(/^\//, "")}`,
"utf-8",
try {
return new Response(
await fs.readFile(
`${path.join(
viteConfig.root,
viteConfig.build.outDir,
)}/${url.replace(/^\//, "")}`,
"utf-8",
),
);
return { text, json: () => text().then(JSON.parse) };
} catch (e: any) {
if (e.code !== "ENOENT") throw e;
return new Response(null, { status: 404 });
}
}

return nodeFetch(url, opts);
Expand Down Expand Up @@ -291,7 +296,7 @@ export function PrerenderPlugin({
if (result.links) {
for (let url of result.links) {
const parsed = new URL(url, "http://localhost");
url = parsed.pathname.replace(/\/$/, '') || '/';
url = parsed.pathname.replace(/\/$/, "") || "/";
// ignore external links and ones we've already picked up
if (seen.has(url) || parsed.origin !== "http://localhost") continue;
seen.add(url);
Expand Down

0 comments on commit 070c20c

Please sign in to comment.