Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 085b9b7

Browse files
committed
Support any fetcher for data fetching
1 parent e423905 commit 085b9b7

File tree

3 files changed

+139
-97
lines changed

3 files changed

+139
-97
lines changed

server/error.ts

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
const regStackLoc = /(http:\/\/localhost:60\d{2}\/.+)(:\d+:\d+)/;
2+
3+
export const errorHtml = (message: string, prefix?: string): string => {
4+
return errorTemplate(
5+
message.split("\n").map((line, i) => {
6+
const ret = line.match(regStackLoc);
7+
if (ret) {
8+
const url = new URL(ret[1]);
9+
line = line.replace(ret[0], `.${url.pathname}${ret[2]}`);
10+
}
11+
if (i === 0 && prefix) {
12+
return `<strong>${prefix} ${line}</strong>`;
13+
}
14+
return line;
15+
}).join("\n"),
16+
);
17+
};
18+
19+
const errorTemplate = (message: string) => `
20+
<!DOCTYPE html>
21+
<html lang="en">
22+
<head>
23+
<meta charset="utf-8">
24+
<title>SSR Error - Aleph.js</title>
25+
<style>
26+
body {
27+
overflow: hidden;
28+
}
29+
.error {
30+
display: flex;
31+
align-items: center;
32+
justify-content: center;
33+
width: 100vw;
34+
height: 100vh;
35+
}
36+
.error .box {
37+
box-sizing: border-box;
38+
position: relative;
39+
max-width: 80%;
40+
max-height: 90%;
41+
overflow: auto;
42+
padding: 24px 36px;
43+
border-radius: 12px;
44+
border: 2px solid rgba(255, 0, 0, 0.8);
45+
background-color: rgba(255, 0, 0, 0.1);
46+
color: rgba(255, 0, 0, 1);
47+
}
48+
.error .logo {
49+
position: absolute;
50+
top: 50%;
51+
left: 50%;
52+
margin-top: -45px;
53+
margin-left: -45px;
54+
opacity: 0.1;
55+
}
56+
.error pre {
57+
position: relative;
58+
line-height: 1.4;
59+
}
60+
.error code {
61+
font-size: 14px;
62+
}
63+
</style>
64+
</head>
65+
<body>
66+
<div class="error">
67+
<div class="box">
68+
<div class="logo">
69+
<svg width="90" height="90" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
70+
<path d="M52.9528 11.1C54.0959 11.1 55.1522 11.7097 55.7239 12.6995C68.5038 34.8259 81.2837 56.9524 94.0636 79.0788C94.642 80.0802 94.6355 81.316 94.0425 82.3088C93.0466 83.9762 92.028 85.6661 91.0325 87.3331C90.4529 88.3035 89.407 88.9 88.2767 88.9C62.7077 88.9 37.0519 88.9 11.4828 88.9C10.3207 88.9 9.25107 88.2693 8.67747 87.2586C7.75465 85.6326 6.81025 84.0065 5.88797 82.3805C5.33314 81.4023 5.34422 80.2041 5.90662 79.2302C18.6982 57.0794 31.4919 34.8415 44.3746 12.6907C44.9474 11.7058 46.0009 11.1 47.1402 11.1C49.0554 11.1 51.0005 11.1 52.9528 11.1Z" stroke="#f00" stroke-width="3.2" stroke-miterlimit="10" stroke-linejoin="round"/>
71+
<path d="M28.2002 72.8H80.8002L45.8187 12.5494" stroke="#f00" stroke-width="3.2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
72+
<path d="M71.4999 72.7L45.1999 27.2L10.6519 87.1991" stroke="#f00" stroke-width="3.2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
73+
<path d="M49.8 35.3L23.5 80.8H93.9333" stroke="#f00" stroke-width="3.2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
74+
</svg>
75+
</div>
76+
<pre><code>${message}</code></pre>
77+
</div>
78+
</div>
79+
</body>
80+
</html>
81+
`;

server/mod.ts

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@ import { getContentType } from "../lib/mime.ts";
55
import type { Routes } from "../lib/route.ts";
66
import util from "../lib/util.ts";
77
import { VERSION } from "../version.ts";
8+
import { errorHtml } from "./error.ts";
89
import { getDeploymentId, initModuleLoaders, loadImportMap, loadJSXConfig } from "./helpers.ts";
9-
import { loadAndFixIndexHtml } from "./html.ts";
10-
import type { HTMLRewriterHandlers, SSR } from "./renderer.ts";
11-
import renderer from "./renderer.ts";
10+
import { type HTMLRewriterHandlers, loadAndFixIndexHtml } from "./html.ts";
11+
import renderer, { type SSR } from "./renderer.ts";
1212
import { content, type CookieOptions, json, setCookieHeader } from "./response.ts";
1313
import { importRouteModule, initRoutes, revive } from "./routing.ts";
1414
import clientModuleTransformer from "./transformer.ts";
@@ -67,7 +67,7 @@ export const serve = (options: ServerOptions = {}) => {
6767
} catch (err) {
6868
if (!(err instanceof Deno.errors.NotFound)) {
6969
log.error(err);
70-
return onError?.(err) ?? new Response(err.message, { status: 500 });
70+
return onError?.(err) ?? new Response(errorHtml(err.message), { status: 500 });
7171
}
7272
}
7373
}
@@ -94,7 +94,7 @@ export const serve = (options: ServerOptions = {}) => {
9494
} catch (err) {
9595
if (!(err instanceof Deno.errors.NotFound)) {
9696
log.error(err);
97-
return onError?.(err) ?? new Response(err.message, { status: 500 });
97+
return onError?.(err) ?? new Response(errorHtml(err.message), { status: 500 });
9898
}
9999
}
100100
}
@@ -131,7 +131,7 @@ export const serve = (options: ServerOptions = {}) => {
131131
} catch (err) {
132132
if (!(err instanceof Deno.errors.NotFound)) {
133133
log.error(err);
134-
return onError?.(err) ?? new Response(err.message, { status: 500 });
134+
return onError?.(err) ?? new Response(errorHtml(err.message), { status: 500 });
135135
}
136136
}
137137
}
@@ -230,7 +230,7 @@ export const serve = (options: ServerOptions = {}) => {
230230
}
231231
}
232232
} catch (err) {
233-
return onError?.(err) ?? new Response(err.message, { status: 500 });
233+
return onError?.(err) ?? new Response(errorHtml(err.message), { status: 500 });
234234
}
235235
}
236236

@@ -247,9 +247,17 @@ export const serve = (options: ServerOptions = {}) => {
247247
req.method !== "GET" || mod.default === undefined || req.headers.get("Accept") === "application/json" ||
248248
!req.headers.get("Accept")?.includes("html")
249249
) {
250+
Object.assign(ctx.params, ret.pathname.groups);
251+
const anyFetcher = dataConfig.any;
252+
if (typeof anyFetcher === "function") {
253+
const res = await anyFetcher(req, ctx);
254+
if (res instanceof Response) {
255+
return res;
256+
}
257+
}
250258
const fetcher = dataConfig[req.method.toLowerCase()];
251259
if (typeof fetcher === "function") {
252-
const res = await fetcher(req, { ...ctx, params: ret.pathname.groups });
260+
const res = await fetcher(req, ctx);
253261
if (res instanceof Response) {
254262
return res;
255263
}
@@ -301,7 +309,7 @@ export const serve = (options: ServerOptions = {}) => {
301309
indexHtml = null;
302310
} else {
303311
log.error("read index.html:", err);
304-
return onError?.(err) ?? new Response(err.message, { status: 500 });
312+
return onError?.(err) ?? new Response(errorHtml(err.message), { status: 500 });
305313
}
306314
}
307315
}

server/renderer.ts

Lines changed: 41 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ import log from "../lib/log.ts";
33
import util from "../lib/util.ts";
44
import type { RouteModule, Routes } from "../lib/route.ts";
55
import { matchRoutes } from "../lib/route.ts";
6+
import { errorHtml } from "./error.ts";
67
import type { DependencyGraph, Module } from "./graph.ts";
78
import { builtinModuleExts, getDeploymentId, getUnoGenerator } from "./helpers.ts";
8-
import type { Comment, Element } from "./html.ts";
9+
import type { Element, HTMLRewriterHandlers } from "./html.ts";
910
import { HTMLRewriter } from "./html.ts";
1011
import { importRouteModule } from "./routing.ts";
1112

@@ -20,11 +21,6 @@ export type SSRContext = {
2021
readonly onError?: (error: unknown) => void;
2122
};
2223

23-
export type HTMLRewriterHandlers = {
24-
element?: (element: Element) => void;
25-
comments?: (element: Comment) => void;
26-
};
27-
2824
export type SSR = {
2925
suspense: true;
3026
render(ssr: SSRContext): Promise<ReadableStream> | ReadableStream;
@@ -33,7 +29,7 @@ export type SSR = {
3329
render(ssr: SSRContext): Promise<string | ReadableStream> | string | ReadableStream;
3430
} | ((ssr: SSRContext) => Promise<string | ReadableStream> | string | ReadableStream);
3531

36-
type SSRResult = {
32+
export type SSRResult = {
3733
context: SSRContext;
3834
errorBoundaryHandlerFilename?: string;
3935
body: ReadableStream | string;
@@ -142,25 +138,14 @@ export default {
142138
}
143139
let message: string;
144140
if (e instanceof Error) {
145-
const regStackLoc = /(http:\/\/localhost:60\d{2}\/.+)(:\d+:\d+)/;
146-
message = (e.stack as string).split("\n").map((line, i) => {
147-
const ret = line.match(regStackLoc);
148-
if (ret) {
149-
const url = new URL(ret[1]);
150-
line = line.replace(ret[0], `.${url.pathname}${ret[2]}`);
151-
}
152-
if (i === 0) {
153-
return `<strong>SSR ${line}</strong>`;
154-
}
155-
return line;
156-
}).join("\n");
141+
message = e.stack as string;
157142
log.error("SSR", e);
158143
} else {
159144
message = e?.toString?.() || String(e);
160145
}
161146
headers.append("Cache-Control", "public, max-age=0, must-revalidate");
162147
headers.append("Content-Type", "text/html; charset=utf-8");
163-
return new Response(errorHtml(message), { headers });
148+
return new Response(errorHtml(message, "SSR"), { headers });
164149
}
165150
} else {
166151
const { mtime, size } = await Deno.lstat("./index.html");
@@ -338,6 +323,8 @@ async function initSSR(
338323
const url = new URL(req.url);
339324
const matches = matchRoutes(url, routes);
340325
const suspenseData: Record<string, unknown> = {};
326+
327+
// import module and fetch data for each matched route
341328
const modules = await Promise.all(matches.map(async ([ret, { filename }]) => {
342329
const mod = await importRouteModule(filename);
343330
const dataConfig: Record<string, unknown> = util.isPlainObject(mod.data) ? mod.data : {};
@@ -348,10 +335,24 @@ async function initSSR(
348335
defaultExport: mod.default,
349336
dataCacheTtl: dataConfig?.cacheTtl as (number | undefined),
350337
};
338+
339+
// assign route params to context
340+
Object.assign(ctx.params, ret.pathname.groups);
341+
342+
// check `any` fetch of data, throw if it returns a response object
343+
const anyFetcher = dataConfig.any;
344+
if (typeof anyFetcher === "function") {
345+
const res = await anyFetcher(req, ctx);
346+
if (res instanceof Response) {
347+
throw res;
348+
}
349+
}
350+
351+
// check `get` of data, if `suspense` is enabled then return a promise instead
351352
const fetcher = dataConfig.get;
352353
if (typeof fetcher === "function") {
353354
const fetchData = async () => {
354-
let res = fetcher(req, { ...ctx, params: rmod.params });
355+
let res = fetcher(req, ctx);
355356
if (res instanceof Promise) {
356357
res = await res;
357358
}
@@ -384,79 +385,31 @@ async function initSSR(
384385
rmod.data = await fetchData();
385386
}
386387
}
388+
387389
return rmod;
388390
}));
389-
const routeModules = modules.filter(({ defaultExport }) => defaultExport !== undefined);
391+
392+
// find error boundary handler
390393
if (routes._error) {
391394
const [_, meta] = routes._error;
392395
const mod = await importRouteModule(meta.filename);
393396
if (typeof mod.default === "function") {
394-
return [url, routeModules, suspenseData, { filename: meta.filename, default: mod.default }];
397+
return [
398+
url,
399+
modules.filter(({ defaultExport }) => defaultExport !== undefined),
400+
suspenseData,
401+
{
402+
filename: meta.filename,
403+
default: mod.default,
404+
},
405+
];
395406
}
396407
}
397-
return [url, routeModules, suspenseData, undefined];
398-
}
399408

400-
const errorHtml = (message: string) => `
401-
<!DOCTYPE html>
402-
<html lang="en">
403-
<head>
404-
<meta charset="utf-8">
405-
<title>SSR Error - Aleph.js</title>
406-
<style>
407-
body {
408-
overflow: hidden;
409-
}
410-
.error {
411-
display: flex;
412-
align-items: center;
413-
justify-content: center;
414-
width: 100vw;
415-
height: 100vh;
416-
}
417-
.error .box {
418-
box-sizing: border-box;
419-
position: relative;
420-
max-width: 80%;
421-
max-height: 90%;
422-
overflow: auto;
423-
padding: 24px 36px;
424-
border-radius: 12px;
425-
border: 2px solid rgba(255, 0, 0, 0.8);
426-
background-color: rgba(255, 0, 0, 0.1);
427-
color: rgba(255, 0, 0, 1);
428-
}
429-
.error .logo {
430-
position: absolute;
431-
top: 50%;
432-
left: 50%;
433-
margin-top: -45px;
434-
margin-left: -45px;
435-
opacity: 0.1;
436-
}
437-
.error pre {
438-
position: relative;
439-
line-height: 1.4;
440-
}
441-
.error code {
442-
font-size: 14px;
443-
}
444-
</style>
445-
</head>
446-
<body>
447-
<div class="error">
448-
<div class="box">
449-
<div class="logo">
450-
<svg width="90" height="90" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
451-
<path d="M52.9528 11.1C54.0959 11.1 55.1522 11.7097 55.7239 12.6995C68.5038 34.8259 81.2837 56.9524 94.0636 79.0788C94.642 80.0802 94.6355 81.316 94.0425 82.3088C93.0466 83.9762 92.028 85.6661 91.0325 87.3331C90.4529 88.3035 89.407 88.9 88.2767 88.9C62.7077 88.9 37.0519 88.9 11.4828 88.9C10.3207 88.9 9.25107 88.2693 8.67747 87.2586C7.75465 85.6326 6.81025 84.0065 5.88797 82.3805C5.33314 81.4023 5.34422 80.2041 5.90662 79.2302C18.6982 57.0794 31.4919 34.8415 44.3746 12.6907C44.9474 11.7058 46.0009 11.1 47.1402 11.1C49.0554 11.1 51.0005 11.1 52.9528 11.1Z" stroke="#f00" stroke-width="3.2" stroke-miterlimit="10" stroke-linejoin="round"/>
452-
<path d="M28.2002 72.8H80.8002L45.8187 12.5494" stroke="#f00" stroke-width="3.2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
453-
<path d="M71.4999 72.7L45.1999 27.2L10.6519 87.1991" stroke="#f00" stroke-width="3.2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
454-
<path d="M49.8 35.3L23.5 80.8H93.9333" stroke="#f00" stroke-width="3.2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
455-
</svg>
456-
</div>
457-
<pre><code>${message}</code></pre>
458-
</div>
459-
</div>
460-
</body>
461-
</html>
462-
`;
409+
return [
410+
url,
411+
modules.filter(({ defaultExport }) => defaultExport !== undefined),
412+
suspenseData,
413+
undefined,
414+
];
415+
}

0 commit comments

Comments
 (0)