Skip to content

Commit

Permalink
Make reading global context sync to test
Browse files Browse the repository at this point in the history
  • Loading branch information
jpreynat committed Jun 24, 2024
1 parent e1a6029 commit 91cc246
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 15 deletions.
6 changes: 3 additions & 3 deletions src/lib/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ export function singleton<R>(execute: () => Promise<R>): () => Promise<R> {
}

// Promises are not shared between requests in Cloudflare Workers
const ctx = await getRequestContext();
const ctx = getRequestContext();
const current = states.get(ctx);
if (current) {
return current;
Expand Down Expand Up @@ -269,7 +269,7 @@ export function singletonMap<Key extends string, Args extends any[], Result>(
const states = new WeakMap<object, Map<string, Promise<Result>>>();

const fn: SingletonFunction<Key, Args, Result> = async (key, ...args) => {
const ctx = await getRequestContext();
const ctx = getRequestContext();
let current = states.get(ctx);
if (current) {
const existing = current.get(key);
Expand All @@ -292,7 +292,7 @@ export function singletonMap<Key extends string, Args extends any[], Result>(
};

fn.isRunning = async (key: string) => {
const ctx = await getRequestContext();
const ctx = getRequestContext();
const current = states.get(ctx);
return current?.has(key) ?? false;
};
Expand Down
14 changes: 7 additions & 7 deletions src/lib/cache/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const memoryCache: CacheBackend = {
name: 'memory',
replication: 'local',
async get(key) {
const memoryCache = await getMemoryCache();
const memoryCache = getMemoryCache();
const memoryEntry = memoryCache.get(key);

console.log(`${memoryEntry ? 'memory hit' : 'memory miss'} for key: ${key}`)
Expand All @@ -23,7 +23,7 @@ export const memoryCache: CacheBackend = {
return null;
},
async set(key, entry) {
const memoryCache = await getMemoryCache();
const memoryCache = getMemoryCache();
// When the entry is immutable, we can cache it for the entire duration.
// Else we cache it for a very short time.
const expiresAt =
Expand All @@ -43,11 +43,11 @@ export const memoryCache: CacheBackend = {
memoryCache.set(key, { ...entry, meta });
},
async del(keys) {
const memoryCache = await getMemoryCache();
const memoryCache = getMemoryCache();
keys.forEach((key) => memoryCache.delete(key));
},
async revalidateTags(tags) {
const memoryCache = await getMemoryCache();
const memoryCache = getMemoryCache();
const keys: string[] = [];

memoryCache.forEach((entry, key) => {
Expand All @@ -67,10 +67,10 @@ export const memoryCache: CacheBackend = {
/**
* In memory cache shared globally.
*/
async function getMemoryCache(): Promise<Map<string, CacheEntry>> {
const ctx: Awaited<ReturnType<typeof getGlobalContext>> & {
function getMemoryCache(): Map<string, CacheEntry> {
const ctx: ReturnType<typeof getGlobalContext> & {
gitbookMemoryCache?: Map<string, CacheEntry>;
} = await getGlobalContext();
} = getGlobalContext();

if (ctx.gitbookMemoryCache) {
console.log('getMemoryCache - cache already exists');
Expand Down
10 changes: 5 additions & 5 deletions src/lib/waitUntil.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getOptionalRequestContext } from '@cloudflare/next-on-pages';
import type { ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types';

let pendings: Array<Promise<unknown>> = [];
Expand All @@ -7,29 +8,28 @@ let pendings: Array<Promise<unknown>> = [];
* This object can be used to store data that should be shared between the middleware and the handler
* and re-used for all requests.
*/
export async function getGlobalContext(): Promise<ExecutionContext | object> {
export function getGlobalContext(): ExecutionContext | object {
if (process.env.NODE_ENV === 'test') {
// Do not try loading the next-on-pages package in tests as it'll fail
return globalThis;
}

// 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');
// const { getOptionalRequestContext } = await import('@cloudflare/next-on-pages');
return getOptionalRequestContext()?.ctx ?? globalThis;
}

/**
* Get a global context object for the current request.
* This object can be used as a key to store request-specific data in a WeakMap.
*/
export async function getRequestContext(): Promise<IncomingRequestCfProperties | object> {
export function getRequestContext(): IncomingRequestCfProperties | object {
if (process.env.NODE_ENV === 'test') {
// Do not try loading the next-on-pages package in tests as it'll fail
return globalThis;
}

// 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()?.cf ?? globalThis;
}

Expand All @@ -47,7 +47,7 @@ export async function waitUntil(promise: Promise<unknown>) {
return;
}

const cloudflareContext = await getGlobalContext();
const cloudflareContext = getGlobalContext();
if ('waitUntil' in cloudflareContext) {
cloudflareContext.waitUntil(promise);
} else {
Expand Down

0 comments on commit 91cc246

Please sign in to comment.