forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest-context.service.ts
More file actions
85 lines (75 loc) · 2.46 KB
/
Copy pathrequest-context.service.ts
File metadata and controls
85 lines (75 loc) · 2.46 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { Injectable } from "@nestjs/common";
import { AsyncLocalStorage } from "node:async_hooks";
import { randomUUID } from "node:crypto";
export type RequestContextStore = {
correlationId: string;
traceId: string;
workerRunId?: string;
workerName?: string;
httpMethod?: string;
httpPath?: string;
merchantId?: string;
userId?: string;
};
export type WorkerContextOptions = {
workerName: string;
correlationId?: string;
attributes?: Record<string, string | undefined>;
};
@Injectable()
export class RequestContextService {
private readonly storage = new AsyncLocalStorage<RequestContextStore>();
runWithContext<T>(
store: RequestContextStore,
callback: () => Promise<T> | T,
): Promise<T> {
return Promise.resolve(this.storage.run(store, callback));
}
runWithWorkerContext<T>(
options: WorkerContextOptions,
callback: () => Promise<T> | T,
): Promise<T> {
const correlationId = options.correlationId ?? randomUUID();
const store: RequestContextStore = {
correlationId,
traceId: correlationId,
workerRunId: randomUUID(),
workerName: options.workerName,
};
return this.runWithContext(store, callback);
}
runWithChildContext<T>(
partial: Partial<RequestContextStore>,
callback: () => Promise<T> | T,
): Promise<T> {
const parent = this.storage.getStore();
const correlationId =
partial.correlationId ?? parent?.correlationId ?? randomUUID();
const store: RequestContextStore = {
correlationId,
traceId: parent?.traceId ?? correlationId,
workerRunId: partial.workerRunId ?? parent?.workerRunId,
workerName: partial.workerName ?? parent?.workerName,
httpMethod: partial.httpMethod ?? parent?.httpMethod,
httpPath: partial.httpPath ?? parent?.httpPath,
merchantId: partial.merchantId ?? parent?.merchantId,
userId: partial.userId ?? parent?.userId,
};
return this.runWithContext(store, callback);
}
getStore(): RequestContextStore | undefined {
return this.storage.getStore();
}
getCorrelationId(): string | undefined {
return this.storage.getStore()?.correlationId;
}
getTraceId(): string | undefined {
return this.storage.getStore()?.traceId;
}
setUserContext(userId?: string, merchantId?: string): void {
const store = this.storage.getStore();
if (!store) return;
if (userId !== undefined) store.userId = userId;
if (merchantId !== undefined) store.merchantId = merchantId;
}
}