Skip to content

Commit f5df40e

Browse files
authored
Use a singleton to store the memory cache in an internal WeakMap for the current request (#2356)
1 parent e13c76e commit f5df40e

File tree

2 files changed

+6
-12
lines changed

2 files changed

+6
-12
lines changed

src/lib/cache/memory.ts

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { CacheBackend, CacheEntry } from './types';
1+
import { CacheBackend } from './types';
22
import { NON_IMMUTABLE_LOCAL_CACHE_MAX_AGE_SECONDS, isCacheEntryImmutable } from './utils';
3-
import { getGlobalContext } from '../waitUntil';
3+
import { singleton } from '../async';
44

55
export const memoryCache: CacheBackend = {
66
name: 'memory',
@@ -66,13 +66,7 @@ export const memoryCache: CacheBackend = {
6666
/**
6767
* With next-on-pages, the code seems to be isolated between the middleware and the handler.
6868
* To share the cache between the two, we use a global variable.
69+
* By using a singleton, we ensure that the cache is only created once and stored in the
70+
* current request context.
6971
*/
70-
async function getMemoryCache(): Promise<Map<string, CacheEntry>> {
71-
let globalThisForMemoryCache: any = await getGlobalContext();
72-
73-
if (!globalThisForMemoryCache.gitbookMemoryCache) {
74-
globalThisForMemoryCache.gitbookMemoryCache = new Map();
75-
}
76-
77-
return globalThisForMemoryCache.gitbookMemoryCache;
78-
}
72+
const getMemoryCache = singleton(async () => new Map());

src/lib/waitUntil.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export async function getGlobalContext(): Promise<object> {
1212

1313
// We lazy-load the next-on-pages package to avoid errors when running tests because of 'server-only'.
1414
const { getOptionalRequestContext } = await import('@cloudflare/next-on-pages');
15-
return getOptionalRequestContext()?.ctx ?? globalThis;
15+
return getOptionalRequestContext()?.cf ?? globalThis;
1616
}
1717

1818
/**

0 commit comments

Comments
 (0)