Skip to content

Commit 5aa1bdc

Browse files
committed
feat: static assets incremental cache
1 parent efc8f25 commit 5aa1bdc

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { debug, error } from "@opennextjs/aws/adapters/logger.js";
2+
import type { CacheValue, IncrementalCache, WithLastModified } from "@opennextjs/aws/types/overrides.js";
3+
import { IgnorableError } from "@opennextjs/aws/utils/error.js";
4+
5+
import { getCloudflareContext } from "../../cloudflare-context.js";
6+
7+
export const CACHE_DIR = "cdn-cgi/_next_cache";
8+
9+
export const NAME = "cf-static-assets-incremental-cache";
10+
11+
/**
12+
* This cache uses KV static assets and is not recommended. It should only be used for applications
13+
* that do NOT want revalidation and ONLY want to serve pre-rendered data.
14+
*/
15+
class StaticAssetsIncrementalCache implements IncrementalCache {
16+
readonly name = NAME;
17+
18+
async get<IsFetch extends boolean = false>(
19+
key: string,
20+
isFetch?: IsFetch
21+
): Promise<WithLastModified<CacheValue<IsFetch>> | null> {
22+
const assets = getCloudflareContext().env.ASSETS;
23+
if (!assets) throw new IgnorableError("No Static Assets");
24+
25+
debug(`Get ${key}`);
26+
27+
try {
28+
const response = await assets.fetch(this.getAssetUrl(key, isFetch));
29+
if (!response.ok) return null;
30+
31+
return {
32+
value: await response.json(),
33+
// __BUILD_TIMESTAMP_MS__ is injected by ESBuild.
34+
lastModified: (globalThis as { __BUILD_TIMESTAMP_MS__?: number }).__BUILD_TIMESTAMP_MS__,
35+
};
36+
} catch (e) {
37+
error("Failed to get from cache", e);
38+
return null;
39+
}
40+
}
41+
42+
async set(): Promise<void> {}
43+
44+
async delete(): Promise<void> {}
45+
46+
protected getAssetUrl(key: string, isFetch?: boolean): string {
47+
const buildId = process.env.NEXT_BUILD_ID ?? "no-build-id";
48+
const name = `${CACHE_DIR}/${buildId}/${key}.${isFetch ? "fetch" : "cache"}`.replace(/\/+/g, "/");
49+
return `http://assets.local/${name}`;
50+
}
51+
}
52+
53+
export default new StaticAssetsIncrementalCache();

0 commit comments

Comments
 (0)