Files
Epicnabbo-Catalogus-Updated…/src/lib/foundation/request-context.ts
T

57 lines
1.5 KiB
TypeScript

import { AsyncLocalStorage } from "node:async_hooks";
import type { IpAddress, RequestId, UserId } from "./types";
export interface RequestStore {
requestId: RequestId;
ip: IpAddress;
userId: UserId | null;
startedAt: number;
}
const als = new AsyncLocalStorage<RequestStore>();
let counter = 0;
function generateRequestId(): RequestId {
counter = (counter + 1) & 0xffff;
return `${Date.now().toString(36)}-${counter.toString(36)}-${crypto.randomUUID().slice(0, 8)}` as RequestId;
}
export function createStore(ip: IpAddress): RequestStore {
return {
requestId: generateRequestId(),
ip,
userId: null,
startedAt: Date.now(),
};
}
export function runWithStore<T>(store: RequestStore, fn: () => T): T {
return als.run(store, fn);
}
// TODO: Check of dit weg kan — niet geïmporteerd in de codebase
export function getRequestStore(): RequestStore | null {
return als.getStore() ?? null;
}
export function getRequestId(): RequestId {
return als.getStore()?.requestId ?? generateRequestId();
}
// TODO: Check of dit weg kan — niet geïmporteerd in de codebase
export function getClientIp(): IpAddress {
return als.getStore()?.ip ?? ("0.0.0.0" as IpAddress);
}
export function setContextUserId(userId: UserId): void {
const store = als.getStore();
if (store) store.userId = userId;
}
// TODO: Check of dit weg kan — niet geïmporteerd in de codebase
export function elapsed(): number {
const store = als.getStore();
return store ? Date.now() - store.startedAt : 0;
}