Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Return proper Response from patched fetch during prerender #105

Merged
merged 2 commits into from
Feb 19, 2024
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
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
Loading