From 728a8f9ca7bc5d6689242b081bedc8f6881282c0 Mon Sep 17 00:00:00 2001 From: Ryan Christian Date: Mon, 19 Feb 2024 00:32:21 -0600 Subject: [PATCH 1/2] feat: Return `Response` from patched fetch --- src/prerender.ts | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/prerender.ts b/src/prerender.ts index 42845a0..2a438ab 100644 --- a/src/prerender.ts +++ b/src/prerender.ts @@ -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); @@ -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); From a551c03a8906674e3be986705c9d9e9f88f21b5f Mon Sep 17 00:00:00 2001 From: Ryan Christian Date: Mon, 19 Feb 2024 00:32:39 -0600 Subject: [PATCH 2/2] test: Revise fetch test to use response --- demo/src/components/LocalFetch.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/demo/src/components/LocalFetch.tsx b/demo/src/components/LocalFetch.tsx index 11eea19..6e636bc 100644 --- a/demo/src/components/LocalFetch.tsx +++ b/demo/src/components/LocalFetch.tsx @@ -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) {