feat: add support for static asset caching (#133)

This commit is contained in:
Sylvain Cau
2022-03-16 16:49:47 +01:00
committed by GitHub
parent 8aa1b250b8
commit 6cbcc27646
9 changed files with 93 additions and 20 deletions
+26 -12
View File
@@ -10,13 +10,7 @@ import {
} from "./deps.ts";
import { Manifest } from "./mod.ts";
import { Bundler } from "./bundle.ts";
import {
ALIVE_URL,
BUILD_ID,
INTERNAL_PREFIX,
JS_PREFIX,
REFRESH_JS_URL,
} from "./constants.ts";
import { ALIVE_URL, BUILD_ID, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts";
import DefaultErrorHandler from "./default_error_page.tsx";
import {
AppModule,
@@ -36,6 +30,7 @@ import {
import { render as internalRender } from "./render.tsx";
import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts";
import { h } from "../runtime/deps.ts";
import { asset, INTERNAL_PREFIX } from "../runtime/utils.ts";
interface StaticFile {
/** The URL to the static file on disk. */
@@ -319,6 +314,9 @@ export class ServerContext {
}
// Add the static file routes.
// each files has 2 static routes:
// - one serving the file at its location without a "cache bursting" mechanism
// - one containing the BUILD_ID in the path that can be cached
for (
const { localUrl, path, size, contentType, etag } of this.#staticFiles
) {
@@ -329,6 +327,15 @@ export class ServerContext {
contentType,
etag,
);
const hashedRoute = sanitizePathToRegex(asset(path));
routes[`GET@${hashedRoute}`] = this.#staticFileHandler(
localUrl,
size,
contentType,
etag,
true,
);
}
const genRender = <Data = undefined>(
@@ -442,18 +449,25 @@ export class ServerContext {
size: number,
contentType: string,
etag: string,
isCacheable?: boolean,
): router.MatchHandler {
return async (req: Request) => {
if (req.headers.get("if-none-match") === etag) {
return new Response(null, { status: 304 });
} else {
const resp = await fetch(localUrl);
const headers = new Headers({
"content-type": contentType,
"content-length": String(size),
"etag": etag,
});
if (isCacheable) {
headers.set("Cache-Control", "public, max-age=31536000, immutable");
}
return new Response(resp.body, {
headers: {
"content-type": contentType,
"content-length": String(size),
"etag": etag,
},
headers,
});
}
};