// context.ts // // Request-scoped context using AsyncLocalStorage. // Allows services to access request data (like the current user) without // needing to pass Call through every function. import { AsyncLocalStorage } from "node:async_hooks"; import { anonymousUser, type User } from "./user"; type RequestContext = { user: User; }; const asyncLocalStorage = new AsyncLocalStorage(); // Run a function within a request context function runWithContext(context: RequestContext, fn: () => T): T { return asyncLocalStorage.run(context, fn); } // Get the current user from context, or AnonymousUser if not in a request function getCurrentUser(): User { const context = asyncLocalStorage.getStore(); return context?.user ?? anonymousUser; } export { getCurrentUser, runWithContext, type RequestContext };