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(); run(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; } }