Skip to content

Commit

Permalink
Add expiry to suspense cache based on revalidate (#790)
Browse files Browse the repository at this point in the history
  • Loading branch information
ostenbom authored Jun 23, 2024
1 parent 40e4f20 commit fa751e3
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/purple-rocks-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@cloudflare/next-on-pages': minor
---

add support for the `revalidate` option in fetch
14 changes: 11 additions & 3 deletions packages/next-on-pages/templates/cache/adaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,12 @@ export class CacheAdaptor {
* @param key Key for the item.
* @param value The value to update.
*/
public async update(key: string, value: string): Promise<void> {
throw new Error(`Method not implemented - ${key}, ${value}`);
public async update(
key: string,
value: string,
revalidate?: number,
): Promise<void> {
throw new Error(`Method not implemented - ${key}, ${value}, ${revalidate}`);
}

/**
Expand All @@ -54,7 +58,11 @@ export class CacheAdaptor {
};

// Update the cache entry.
const updateOp = this.update(key, JSON.stringify(newEntry));
const updateOp = this.update(
key,
JSON.stringify(newEntry),
value.revalidate,
);

switch (newEntry.value?.kind) {
case 'FETCH': {
Expand Down
10 changes: 6 additions & 4 deletions packages/next-on-pages/templates/cache/cache-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ export default class CacheApiAdaptor extends CacheAdaptor {
return response ? response.text() : null;
}

public override async update(key: string, value: string) {
public override async update(
key: string,
value: string,
revalidate?: number,
) {
const cache = await caches.open(this.cacheName);

// The max-age to use for the cache entry.
const maxAge = '31536000'; // 1 year

const maxAge = revalidate ?? '31536000'; // 1 year
const response = new Response(value, {
headers: new Headers({
'cache-control': `max-age=${maxAge}`,
Expand Down
13 changes: 12 additions & 1 deletion packages/next-on-pages/templates/cache/kv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,21 @@ export default class KVAdaptor extends CacheAdaptor {
return value ?? null;
}

public override async update(key: string, value: string) {
public override async update(
key: string,
value: string,
revalidate?: number,
) {
const expiry = revalidate
? {
expirationTtl: revalidate,
}
: {};

await process.env.__NEXT_ON_PAGES__KV_SUSPENSE_CACHE?.put(
this.buildCacheKey(key),
value,
expiry,
);
}
}

0 comments on commit fa751e3

Please sign in to comment.