forked from denoland/fresh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.ts
More file actions
100 lines (91 loc) · 2.38 KB
/
render.ts
File metadata and controls
100 lines (91 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import {
type AnyComponent,
type FunctionComponent,
h,
type RenderableProps,
type VNode,
} from "preact";
import type { Context } from "./context.ts";
import { recordSpanError, tracer } from "./otel.ts";
export type AsyncAnyComponent<P> = {
(
props: RenderableProps<P>,
// deno-lint-ignore no-explicit-any
context?: any,
// deno-lint-ignore no-explicit-any
): Promise<VNode<any> | Response | null>;
displayName?: string;
defaultProps?: Partial<P> | undefined;
};
// deno-lint-ignore no-explicit-any
export function isAsyncAnyComponent(fn: any): fn is AsyncAnyComponent<any> {
return typeof fn === "function" && fn.constructor.name === "AsyncFunction";
}
export async function renderAsyncAnyComponent<Props>(
fn: AsyncAnyComponent<Props>,
props: RenderableProps<Props>,
) {
return await tracer.startActiveSpan(
"invoke async component",
async (span) => {
span.setAttribute("fresh.span_type", "fs_routes/async_component");
try {
const result = (await fn(props)) as VNode | Response;
span.setAttribute(
"fresh.component_response",
result instanceof Response ? "http" : "jsx",
);
return result;
} catch (err) {
recordSpanError(span, err);
throw err;
} finally {
span.end();
}
},
);
}
export type PageProps<Data = unknown, T = unknown> =
& Pick<
Context<T>,
| "config"
| "url"
| "req"
| "params"
| "info"
| "state"
| "isPartial"
| "Component"
| "error"
>
& { data: Data };
export interface ComponentDef<Data, State> {
props: PageProps<Data, State> | null;
component: AnyComponent<PageProps<Data, State>>;
}
export async function renderRouteComponent<State>(
ctx: Context<State>,
def: ComponentDef<unknown, State>,
child: FunctionComponent,
): Promise<VNode | Response> {
const vnodeProps: PageProps<unknown, State> = {
Component: child,
config: ctx.config,
data: def.props,
error: ctx.error,
info: ctx.info,
isPartial: ctx.isPartial,
params: ctx.params,
req: ctx.request,
state: ctx.state,
url: ctx.url,
};
if (isAsyncAnyComponent(def.component)) {
const result = await renderAsyncAnyComponent(def.component, vnodeProps);
if (result instanceof Response) {
return result;
}
return result;
}
return h(def.component, vnodeProps) as VNode;
}