Skip to content

Commit

Permalink
Use a singleton to store the memory cache in an internal WeakMap for …
Browse files Browse the repository at this point in the history
…the current request (#2356)
  • Loading branch information
jpreynat authored Jun 24, 2024
1 parent e13c76e commit f5df40e
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 12 deletions.
16 changes: 5 additions & 11 deletions src/lib/cache/memory.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CacheBackend, CacheEntry } from './types';
import { CacheBackend } from './types';
import { NON_IMMUTABLE_LOCAL_CACHE_MAX_AGE_SECONDS, isCacheEntryImmutable } from './utils';
import { getGlobalContext } from '../waitUntil';
import { singleton } from '../async';

export const memoryCache: CacheBackend = {
name: 'memory',
Expand Down Expand Up @@ -66,13 +66,7 @@ export const memoryCache: CacheBackend = {
/**
* With next-on-pages, the code seems to be isolated between the middleware and the handler.
* To share the cache between the two, we use a global variable.
* By using a singleton, we ensure that the cache is only created once and stored in the
* current request context.
*/
async function getMemoryCache(): Promise<Map<string, CacheEntry>> {
let globalThisForMemoryCache: any = await getGlobalContext();

if (!globalThisForMemoryCache.gitbookMemoryCache) {
globalThisForMemoryCache.gitbookMemoryCache = new Map();
}

return globalThisForMemoryCache.gitbookMemoryCache;
}
const getMemoryCache = singleton(async () => new Map());
2 changes: 1 addition & 1 deletion src/lib/waitUntil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function getGlobalContext(): Promise<object> {

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

/**
Expand Down

0 comments on commit f5df40e

Please sign in to comment.