Skip to content

Commit 070c20c

Browse files
authored
Merge pull request #105 from preactjs/feat/patched-fetch-response
feat: Return proper `Response` from patched `fetch` during prerender
2 parents 44d6cb9 + a551c03 commit 070c20c

2 files changed

Lines changed: 16 additions & 10 deletions

File tree

demo/src/components/LocalFetch.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ const cache = new Map();
44

55
async function load(url: string) {
66
const res = await fetch(url);
7-
return await res.text();
7+
if (res.ok) return await res.text();
8+
throw new Error(`Failed to fetch ${url}!`);
89
}
910

1011
function useFetch(url: string) {

src/prerender.ts

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -169,15 +169,20 @@ export function PrerenderPlugin({
169169
// @ts-ignore
170170
globalThis.fetch = async (url: string, opts: RequestInit | undefined) => {
171171
if (/^\//.test(url)) {
172-
const text = () =>
173-
fs.readFile(
174-
`${path.join(
175-
viteConfig.root,
176-
viteConfig.build.outDir,
177-
)}/${url.replace(/^\//, "")}`,
178-
"utf-8",
172+
try {
173+
return new Response(
174+
await fs.readFile(
175+
`${path.join(
176+
viteConfig.root,
177+
viteConfig.build.outDir,
178+
)}/${url.replace(/^\//, "")}`,
179+
"utf-8",
180+
),
179181
);
180-
return { text, json: () => text().then(JSON.parse) };
182+
} catch (e: any) {
183+
if (e.code !== "ENOENT") throw e;
184+
return new Response(null, { status: 404 });
185+
}
181186
}
182187

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

0 commit comments

Comments
 (0)