feat: support async route components (#1388)

This commit is contained in:
Marvin Hagemeister
2023-07-12 21:09:56 +02:00
committed by GitHub
parent e2a1bf8643
commit 62a5613a46
20 changed files with 564 additions and 96 deletions
+122 -54
View File
@@ -32,12 +32,17 @@ import {
Route,
RouteModule,
RouterOptions,
RouterState,
ServeHandlerInfo,
UnknownPage,
UnknownPageModule,
} from "./types.ts";
import { render as internalRender } from "./render.ts";
import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts";
import { DEFAULT_RENDER_FN, render as internalRender } from "./render.ts";
import {
ContentSecurityPolicy,
ContentSecurityPolicyDirectives,
SELF,
} from "../runtime/csp.ts";
import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts";
import {
Builder,
@@ -52,10 +57,6 @@ const DEFAULT_CONN_INFO: ServeHandlerInfo = {
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
};
interface RouterState {
state: Record<string, unknown>;
}
function isObject(value: unknown) {
return typeof value === "object" &&
!Array.isArray(value) &&
@@ -595,6 +596,58 @@ export class ServerContext {
};
}
const dependenciesFn = (path: string) => {
const snapshot = this.#maybeBuildSnapshot();
return snapshot?.dependencies(path) ?? [];
};
const renderNotFound = async <Data = undefined>(
req: Request,
params: Record<string, string>,
// deno-lint-ignore no-explicit-any
ctx?: any,
data?: Data,
error?: unknown,
) => {
const notFound = this.#notFound;
if (!notFound.component) {
return sendResponse(["Not found.", undefined], {
status: Status.NotFound,
isDev: this.#dev,
statusText: undefined,
headers: undefined,
});
}
const imports: string[] = [];
const resp = await internalRender({
request: req,
context: ctx,
route: notFound,
islands: this.#islands,
plugins: this.#plugins,
app: this.#app,
imports,
dependenciesFn,
renderFn: this.#renderFn,
url: new URL(req.url),
params,
data,
state: ctx?.state,
error,
});
if (resp instanceof Response) {
return resp;
}
return sendResponse(resp, {
status: Status.NotFound,
isDev: this.#dev,
statusText: undefined,
headers: undefined,
});
};
const genRender = <Data = undefined>(
route: Route<Data> | UnknownPage | ErrorPage,
status: number,
@@ -604,7 +657,8 @@ export class ServerContext {
return (
req: Request,
params: Record<string, string>,
state?: Record<string, unknown>,
// deno-lint-ignore no-explicit-any
ctx?: any,
error?: unknown,
) => {
return async (data?: Data, options?: RenderOptions) => {
@@ -612,65 +666,42 @@ export class ServerContext {
throw new Error("This page does not have a component to render.");
}
if (
typeof route.component === "function" &&
route.component.constructor.name === "AsyncFunction"
) {
throw new Error(
"Async components are not supported. Fetch data inside of a route handler, as described in the docs: https://fresh.deno.dev/docs/getting-started/fetching-data",
);
}
const resp = await internalRender({
request: req,
context: {
...ctx,
async renderNotFound() {
return await renderNotFound(req, params, ctx, data, error);
},
},
route,
islands: this.#islands,
plugins: this.#plugins,
app: this.#app,
imports,
dependenciesFn: (path) => {
const snapshot = this.#maybeBuildSnapshot();
return snapshot?.dependencies(path) ?? [];
},
dependenciesFn,
renderFn: this.#renderFn,
url: new URL(req.url),
params,
data,
state,
state: ctx?.state,
error,
});
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
const [body, csp] = resp;
if (csp) {
if (this.#dev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers["content-security-policy-report-only"] = directive;
} else {
headers["content-security-policy"] = directive;
}
if (resp instanceof Response) {
return resp;
}
return new Response(body, {
return sendResponse(resp, {
status: options?.status ?? status,
statusText: options?.statusText,
headers: options?.headers
? { ...headers, ...options.headers }
: headers,
headers: options?.headers,
isDev: this.#dev,
});
};
};
};
const createUnknownRender = genRender(this.#notFound, Status.NotFound);
for (const route of this.#routes) {
if (this.#routerOptions.trailingSlash && route.pattern != "/") {
route.pattern += "/";
@@ -682,8 +713,10 @@ export class ServerContext {
(route.handler as Handler)(req, {
...ctx,
params,
render: createRender(req, params, ctx.state),
renderNotFound: createUnknownRender(req, params, ctx.state),
render: createRender(req, params, ctx),
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
}),
};
} else {
@@ -697,8 +730,10 @@ export class ServerContext {
handler(req, {
...ctx,
params,
render: createRender(req, params, ctx.state),
renderNotFound: createUnknownRender(req, params, ctx.state),
render: createRender(req, params, ctx),
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
});
}
}
@@ -712,7 +747,9 @@ export class ServerContext {
req,
{
...ctx,
render: createUnknownRender(req, {}),
render() {
return renderNotFound(req, {}, ctx);
},
},
);
@@ -843,10 +880,6 @@ export class ServerContext {
};
}
const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
render();
};
const DEFAULT_ROUTER_OPTIONS: RouterOptions = {
trailingSlash: false,
};
@@ -1099,3 +1132,38 @@ async function readDenoConfig(
dir = parent;
}
}
function sendResponse(
resp: [string, ContentSecurityPolicy | undefined],
options: {
status: number;
statusText: string | undefined;
headers?: HeadersInit;
isDev: boolean;
},
) {
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
const [body, csp] = resp;
if (csp) {
if (options.isDev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers["content-security-policy-report-only"] = directive;
} else {
headers["content-security-policy"] = directive;
}
}
return new Response(body, {
status: options.status,
statusText: options.statusText,
headers: options.headers ? { ...headers, ...options.headers } : headers,
});
}