mirror of
https://github.com/nicotsx/zerobyte.git
synced 2026-06-02 21:16:14 -04:00
25 lines
616 B
TypeScript
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;
|