Skip to content

Commit

Permalink
refactor: extract proxy creation into utility
Browse files Browse the repository at this point in the history
  • Loading branch information
james-elicx committed Oct 18, 2024
1 parent a91ac71 commit 335fac5
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 10 deletions.
18 changes: 18 additions & 0 deletions packages/cloudflare/src/cli/templates/utils/create-als-proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { AsyncLocalStorage } from "node:async_hooks";

/**
* Creates a proxy for to use for an instance of AsyncLocalStorage.
*
* @param als AsyncLocalStorage instance.
*/
export function createALSProxy<T>(als: AsyncLocalStorage<T>) {
return new Proxy(
{},
{
ownKeys: () => Reflect.ownKeys(als.getStore()!),
getOwnPropertyDescriptor: (_, ...args) => Reflect.getOwnPropertyDescriptor(als.getStore()!, ...args),
get: (_, property) => Reflect.get(als.getStore()!, property),
set: (_, property, value) => Reflect.set(als.getStore()!, property, value),
}
);
}
1 change: 1 addition & 0 deletions packages/cloudflare/src/cli/templates/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./create-als-proxy";
12 changes: 2 additions & 10 deletions packages/cloudflare/src/cli/templates/worker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { AsyncLocalStorage } from "node:async_hooks";
import type { IncomingMessage } from "node:http";
import Stream from "node:stream";
import { createALSProxy } from "./utils";

import type { ExportedHandler, Fetcher } from "@cloudflare/workers-types";
import type { NextConfig } from "next";
Expand All @@ -16,16 +17,7 @@ const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();

// Note: this symbol needs to be kept in sync with the one defined in `src/api/get-cloudflare-context.ts`
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any)[Symbol.for("__cloudflare-context__")] = new Proxy(
{},
{
ownKeys: () => Reflect.ownKeys(cloudflareContextALS.getStore()!),
getOwnPropertyDescriptor: (_, ...args) =>
Reflect.getOwnPropertyDescriptor(cloudflareContextALS.getStore()!, ...args),
get: (_, property) => Reflect.get(cloudflareContextALS.getStore()!, property),
set: (_, property, value) => Reflect.set(cloudflareContextALS.getStore()!, property, value),
}
);
(globalThis as any)[Symbol.for("__cloudflare-context__")] = createALSProxy(cloudflareContextALS);

// Injected at build time
const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG ?? "{}");
Expand Down

0 comments on commit 335fac5

Please sign in to comment.