Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import { Injectable, Scope } from '@nestjs/common'; export interface RequestContext { requestId: string; correlationId: string; tenantId?: string; userId?: string; deviceType?: 'web' | 'mobile' | 'public'; clientApp?: string; ipAddress?: string; userAgent?: string; apiVersion?: string; startTime: number; } @Injectable({ scope: Scope.DEFAULT }) export class RequestContextService { private readonly contextMap = new Map<string, RequestContext>(); set(requestId: string, context: RequestContext): void { this.contextMap.set(requestId, context); } get(requestId: string): RequestContext | undefined { return this.contextMap.get(requestId); } clear(requestId: string): void { this.contextMap.delete(requestId); } buildFromRequest(req: any): RequestContext { return { requestId: req['requestId'] || req.headers['x-request-id'] || 'unknown', correlationId: req['correlationId'] || req.headers['x-correlation-id'] || 'unknown', tenantId: req.user?.tenantId, userId: req.user?.userId || req.user?._id, deviceType: this.detectDeviceType(req), clientApp: req.headers['x-client-app'] as string, ipAddress: req.ip || req.connection?.remoteAddress, userAgent: req.headers['user-agent'] as string, apiVersion: this.detectApiVersion(req.url), startTime: Date.now(), }; } private detectDeviceType(req: any): 'web' | 'mobile' | 'public' { const url: string = req.url || ''; if (url.includes('/mobile/') || url.includes('/api/v1/mobile')) return 'mobile'; if (url.includes('/api/v1/public')) return 'public'; return 'web'; } private detectApiVersion(url: string): string { const match = url.match(/\/api\/(v\d+)\//); return match ? match[1] : 'v1'; } } |