Files
zerobyte/app/server/core/request-context.ts
2026-04-22 22:04:46 +02:00

25 lines
616 B
TypeScript

import { AsyncLocalStorage } from "node:async_hooks";
type RequestContext = {
organizationId: string;
userId?: string;
};
const requestContextStorage = new AsyncLocalStorage<RequestContext>();
export const withContext = <T>(context: RequestContext, fn: () => T): T => {
return requestContextStorage.run(context, fn);
};
const getRequestContext = (): RequestContext => {
const context = requestContextStorage.getStore();
if (!context?.organizationId) {
throw new Error("Organization context is missing");
}
return context;
};
export const getOrganizationId = () => getRequestContext().organizationId;