UNPKG

@redwoodjs/sdk

Version:

Build fast, server-driven webapps on Cloudflare with SSR, RSC, and realtime

34 lines (33 loc) 1.11 kB
import { AsyncLocalStorage } from "async_hooks"; const requestContextStore = new AsyncLocalStorage(); const requestContextBase = {}; const CONTEXT_KEYS = ["request", "params", "data", "headers", "rw", "cf"]; CONTEXT_KEYS.forEach((key) => { Object.defineProperty(requestContextBase, key, { enumerable: true, configurable: false, get: function () { const store = requestContextStore.getStore(); return store ? store[key] : undefined; }, }); }); export const requestContext = Object.freeze(requestContextBase); export function getRequestContext() { const store = requestContextStore.getStore(); if (!store) { throw new Error("Request context not found"); } return store; } export function runWithRequestContext(context, fn) { return requestContextStore.run(context, fn); } export function runWithRequestContextOverrides(overrides, fn) { const context = requestContextStore.getStore(); const newContext = { ...context, ...overrides, }; return requestContextStore.run(newContext, fn); }