refactor: asset caching via query param (#192)

This updates the asset caching to use a cache busting query string,
rather than a totally separate path. This makes it safer to apply
caching automatically to things like `<img>` tags, as the path does not
change anymore.
This commit is contained in:
Luca Casonato
2022-05-16 17:39:22 +00:00
committed by GitHub
parent c28d2ff863
commit cf438a7879
6 changed files with 56 additions and 24 deletions
+22 -5
View File
@@ -1,13 +1,30 @@
export const INTERNAL_PREFIX = "/_frsh";
export const STATIC_PREFIX = `/static`;
export const ASSET_CACHE_BUST_KEY = "__frsh_c";
export const IS_BROWSER = typeof document !== "undefined";
/**
* Return a path "hashed" with the BUILD_ID. of a static file
* Such path will be served by the server with a Cache-Control of 1 year.
* @param path a path to a file in the static folder asset. e.g. /style.css
* Create a "locked" asset path. This differs from a plain path in that it is
* specific to the current version of the application, and as such can be safely
* served with a very long cache lifetime (1 year).
*/
export function asset(path: string) {
return `${INTERNAL_PREFIX}${STATIC_PREFIX}/${__FRSH_BUILD_ID}${path}`;
if (!path.startsWith("/") || path.startsWith("//")) return path;
try {
const url = new URL(path, "https://freshassetcache.local");
if (
url.protocol !== "https:" || url.host !== "freshassetcache.local" ||
url.searchParams.has(ASSET_CACHE_BUST_KEY)
) {
return path;
}
url.searchParams.set(ASSET_CACHE_BUST_KEY, __FRSH_BUILD_ID);
return url.pathname + url.search + url.hash;
} catch (err) {
console.warn(
`Failed to create asset() URL, falling back to regular path ('${path}'):`,
err,
);
return path;
}
}
+19
View File
@@ -0,0 +1,19 @@
import { assertEquals } from "../../tests/deps.ts";
import { asset } from "./utils.ts";
globalThis.__FRSH_BUILD_ID = "ID123";
Deno.test("asset", () => {
assertEquals(asset("/test.png"), "/test.png?__frsh_c=ID123");
assertEquals(asset("/test?f=1"), "/test?f=1&__frsh_c=ID123");
assertEquals(asset("/test#foo"), "/test?__frsh_c=ID123#foo");
assertEquals(asset("/test?f=1#foo"), "/test?f=1&__frsh_c=ID123#foo");
assertEquals(asset("./test.png"), "./test.png");
assertEquals(asset("//example.com/logo.png"), "//example.com/logo.png");
assertEquals(asset("/test.png?__frsh_c=1"), "/test.png?__frsh_c=1");
assertEquals(
asset("https://example.com/logo.png"),
"https://example.com/logo.png",
);
});