Use AsyncLocalStorage to provide request context so services can access the current user without needing Call passed through every function. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
28 lines
856 B
TypeScript
28 lines
856 B
TypeScript
// 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 MaybeUser } from "./user";
|
|
|
|
type RequestContext = {
|
|
user: MaybeUser;
|
|
};
|
|
|
|
const asyncLocalStorage = new AsyncLocalStorage<RequestContext>();
|
|
|
|
// Run a function within a request context
|
|
function runWithContext<T>(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(): MaybeUser {
|
|
const context = asyncLocalStorage.getStore();
|
|
return context?.user ?? AnonymousUser;
|
|
}
|
|
|
|
export { getCurrentUser, runWithContext, type RequestContext };
|