56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
|
export interface AuthenticatedDeviceContextValue {
|
|
deviceId: string;
|
|
userId: string;
|
|
}
|
|
|
|
interface RequestContextState {
|
|
authenticatedDevice: AuthenticatedDeviceContextValue | null;
|
|
legacyDeviceId: string | null;
|
|
}
|
|
|
|
@Injectable()
|
|
export class RequestContextService {
|
|
private readonly storage = new AsyncLocalStorage<RequestContextState>();
|
|
|
|
run<T>(callback: () => T): T {
|
|
return this.storage.run(
|
|
{
|
|
authenticatedDevice: null,
|
|
legacyDeviceId: null,
|
|
},
|
|
callback,
|
|
);
|
|
}
|
|
|
|
getAuthenticatedDevice(): AuthenticatedDeviceContextValue | null {
|
|
return this.storage.getStore()?.authenticatedDevice ?? null;
|
|
}
|
|
|
|
setAuthenticatedDevice(device: AuthenticatedDeviceContextValue): void {
|
|
const store = this.storage.getStore();
|
|
|
|
if (!store) {
|
|
return;
|
|
}
|
|
|
|
store.authenticatedDevice = device;
|
|
}
|
|
|
|
getLegacyDeviceId(): string | null {
|
|
return this.storage.getStore()?.legacyDeviceId ?? null;
|
|
}
|
|
|
|
setLegacyDeviceId(deviceId: string): void {
|
|
const store = this.storage.getStore();
|
|
|
|
if (!store) {
|
|
return;
|
|
}
|
|
|
|
store.legacyDeviceId = deviceId;
|
|
}
|
|
}
|