Files
electric-cherry/src/lib/server/auth/request-context.ts
T

24 lines
734 B
TypeScript

import { AsyncLocalStorage } from 'node:async_hooks';
const requester = new AsyncLocalStorage<{ username: string | null; active: boolean }>();
/** Use only the authenticated session, and stop attribution when the request finishes. */
export async function withRequestUsername<T>(
username: string | null,
work: () => T | Promise<T>
): Promise<T> {
const context = { username, active: true };
return requester.run(context, async () => {
try {
return await work();
} finally {
context.active = false;
}
});
}
export function currentRequestUsername(): string | null {
const context = requester.getStore();
return context?.active ? context.username : null;
}