This commit is contained in:
1 parent
8efd032cc6
commit
df38dccbf1
735 files changed
+128321
-120870
No files matched your search
@@ -2,10 +2,10 @@ 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;
|
||||
requestId: RequestId;
|
||||
ip: IpAddress;
|
||||
userId: UserId | null;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
const als = new AsyncLocalStorage<RequestStore>();
|
||||
@@ -13,41 +13,41 @@ 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;
|
||||
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(),
|
||||
};
|
||||
return {
|
||||
requestId: generateRequestId(),
|
||||
ip,
|
||||
userId: null,
|
||||
startedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
export function runWithStore<T>(store: RequestStore, fn: () => T): T {
|
||||
return als.run(store, fn);
|
||||
return als.run(store, fn);
|
||||
}
|
||||
|
||||
export function getRequestStore(): RequestStore | null {
|
||||
return als.getStore() ?? null;
|
||||
return als.getStore() ?? null;
|
||||
}
|
||||
|
||||
export function getRequestId(): RequestId {
|
||||
return als.getStore()?.requestId ?? generateRequestId();
|
||||
return als.getStore()?.requestId ?? generateRequestId();
|
||||
}
|
||||
|
||||
export function getClientIp(): IpAddress {
|
||||
return als.getStore()?.ip ?? ("0.0.0.0" as 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;
|
||||
const store = als.getStore();
|
||||
if (store) store.userId = userId;
|
||||
}
|
||||
|
||||
export function elapsed(): number {
|
||||
const store = als.getStore();
|
||||
return store ? Date.now() - store.startedAt : 0;
|
||||
const store = als.getStore();
|
||||
return store ? Date.now() - store.startedAt : 0;
|
||||
}
|
||||
Reference in new issue
Block a user