@nest-omni/core 3.1.2-7 → 3.1.2-9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/audit/audit.module.d.ts +10 -0
  2. package/audit/audit.module.js +254 -0
  3. package/audit/controllers/audit.controller.d.ts +20 -0
  4. package/audit/controllers/audit.controller.js +142 -0
  5. package/audit/controllers/index.d.ts +1 -0
  6. package/audit/controllers/index.js +17 -0
  7. package/audit/decorators/audit-controller.decorator.d.ts +5 -0
  8. package/audit/decorators/audit-controller.decorator.js +17 -0
  9. package/audit/decorators/audit-operation.decorator.d.ts +7 -0
  10. package/audit/decorators/audit-operation.decorator.js +25 -0
  11. package/audit/decorators/entity-audit.decorator.d.ts +10 -0
  12. package/audit/decorators/entity-audit.decorator.js +70 -0
  13. package/audit/decorators/index.d.ts +3 -0
  14. package/audit/decorators/index.js +19 -0
  15. package/audit/dto/audit-log-query.dto.d.ts +14 -0
  16. package/audit/dto/audit-log-query.dto.js +95 -0
  17. package/audit/dto/begin-transaction.dto.d.ts +3 -0
  18. package/audit/dto/begin-transaction.dto.js +22 -0
  19. package/audit/dto/compare-entities.dto.d.ts +6 -0
  20. package/audit/dto/compare-entities.dto.js +44 -0
  21. package/audit/dto/index.d.ts +5 -0
  22. package/audit/dto/index.js +21 -0
  23. package/audit/dto/pre-check-restore.dto.d.ts +5 -0
  24. package/audit/dto/pre-check-restore.dto.js +32 -0
  25. package/audit/dto/restore-entity.dto.d.ts +9 -0
  26. package/audit/dto/restore-entity.dto.js +53 -0
  27. package/audit/entities/entity-audit-log.entity.d.ts +23 -0
  28. package/audit/entities/entity-audit-log.entity.js +110 -0
  29. package/audit/entities/entity-transaction.entity.d.ts +21 -0
  30. package/audit/entities/entity-transaction.entity.js +80 -0
  31. package/audit/entities/index.d.ts +4 -0
  32. package/audit/entities/index.js +20 -0
  33. package/audit/entities/manual-operation-log.entity.d.ts +13 -0
  34. package/audit/entities/manual-operation-log.entity.js +65 -0
  35. package/audit/entities/operation-template.entity.d.ts +11 -0
  36. package/audit/entities/operation-template.entity.js +65 -0
  37. package/audit/enums/audit.enums.d.ts +42 -0
  38. package/audit/enums/audit.enums.js +53 -0
  39. package/audit/enums/index.d.ts +1 -0
  40. package/audit/enums/index.js +17 -0
  41. package/audit/index.d.ts +12 -0
  42. package/audit/index.js +48 -0
  43. package/audit/interceptors/audit.interceptor.d.ts +12 -0
  44. package/audit/interceptors/audit.interceptor.js +95 -0
  45. package/audit/interceptors/index.d.ts +1 -0
  46. package/audit/interceptors/index.js +17 -0
  47. package/audit/interfaces/audit.interfaces.d.ts +180 -0
  48. package/audit/interfaces/audit.interfaces.js +2 -0
  49. package/audit/interfaces/index.d.ts +1 -0
  50. package/audit/interfaces/index.js +17 -0
  51. package/audit/services/audit-context.service.d.ts +10 -0
  52. package/audit/services/audit-context.service.js +55 -0
  53. package/audit/services/audit-strategy.service.d.ts +19 -0
  54. package/audit/services/audit-strategy.service.js +89 -0
  55. package/audit/services/entity-audit.service.d.ts +65 -0
  56. package/audit/services/entity-audit.service.js +626 -0
  57. package/audit/services/index.d.ts +6 -0
  58. package/audit/services/index.js +22 -0
  59. package/audit/services/multi-database.service.d.ts +10 -0
  60. package/audit/services/multi-database.service.js +59 -0
  61. package/audit/services/operation-description.service.d.ts +21 -0
  62. package/audit/services/operation-description.service.js +213 -0
  63. package/audit/services/transaction-audit.service.d.ts +22 -0
  64. package/audit/services/transaction-audit.service.js +201 -0
  65. package/audit/subscribers/entity-audit.subscriber.d.ts +14 -0
  66. package/audit/subscribers/entity-audit.subscriber.js +136 -0
  67. package/audit/subscribers/index.d.ts +1 -0
  68. package/audit/subscribers/index.js +17 -0
  69. package/common/utils.d.ts +1 -0
  70. package/common/utils.js +6 -0
  71. package/http-client/config/http-client.config.d.ts +6 -0
  72. package/http-client/config/http-client.config.js +87 -0
  73. package/http-client/config/index.d.ts +1 -0
  74. package/http-client/config/index.js +17 -0
  75. package/http-client/decorators/http-client.decorators.d.ts +72 -0
  76. package/http-client/decorators/http-client.decorators.js +204 -0
  77. package/http-client/decorators/index.d.ts +1 -0
  78. package/http-client/decorators/index.js +17 -0
  79. package/http-client/entities/http-log.entity.d.ts +98 -0
  80. package/http-client/entities/http-log.entity.js +143 -0
  81. package/http-client/entities/index.d.ts +1 -0
  82. package/http-client/entities/index.js +17 -0
  83. package/http-client/errors/http-client.errors.d.ts +56 -0
  84. package/http-client/errors/http-client.errors.js +149 -0
  85. package/http-client/errors/index.d.ts +1 -0
  86. package/http-client/errors/index.js +17 -0
  87. package/http-client/examples/advanced-usage.example.d.ts +23 -0
  88. package/http-client/examples/advanced-usage.example.js +332 -0
  89. package/http-client/examples/auth-with-waiting-lock.example.d.ts +17 -0
  90. package/http-client/examples/auth-with-waiting-lock.example.js +336 -0
  91. package/http-client/examples/basic-usage.example.d.ts +53 -0
  92. package/http-client/examples/basic-usage.example.js +161 -0
  93. package/http-client/examples/index.d.ts +3 -0
  94. package/http-client/examples/index.js +19 -0
  95. package/http-client/examples/multi-api-configuration.example.d.ts +98 -0
  96. package/http-client/examples/multi-api-configuration.example.js +353 -0
  97. package/http-client/http-client.module.d.ts +11 -0
  98. package/http-client/http-client.module.js +257 -0
  99. package/http-client/index.d.ts +10 -0
  100. package/http-client/index.js +27 -0
  101. package/http-client/interfaces/api-client-config.interface.d.ts +152 -0
  102. package/http-client/interfaces/api-client-config.interface.js +12 -0
  103. package/http-client/interfaces/http-client-config.interface.d.ts +123 -0
  104. package/http-client/interfaces/http-client-config.interface.js +2 -0
  105. package/http-client/services/api-client-registry.service.d.ts +41 -0
  106. package/http-client/services/api-client-registry.service.js +412 -0
  107. package/http-client/services/cache.service.d.ts +24 -0
  108. package/http-client/services/cache.service.js +264 -0
  109. package/http-client/services/circuit-breaker.service.d.ts +33 -0
  110. package/http-client/services/circuit-breaker.service.js +180 -0
  111. package/http-client/services/http-client.service.d.ts +60 -0
  112. package/http-client/services/http-client.service.js +504 -0
  113. package/http-client/services/http-log-query.service.d.ts +76 -0
  114. package/http-client/services/http-log-query.service.js +590 -0
  115. package/http-client/services/http-replay.service.d.ts +58 -0
  116. package/http-client/services/http-replay.service.js +266 -0
  117. package/http-client/services/index.d.ts +7 -0
  118. package/http-client/services/index.js +23 -0
  119. package/http-client/services/log-cleanup.service.d.ts +64 -0
  120. package/http-client/services/log-cleanup.service.js +268 -0
  121. package/http-client/services/logging.service.d.ts +36 -0
  122. package/http-client/services/logging.service.js +445 -0
  123. package/http-client/utils/call-stack-extractor.util.d.ts +29 -0
  124. package/http-client/utils/call-stack-extractor.util.js +138 -0
  125. package/http-client/utils/context-extractor.util.d.ts +44 -0
  126. package/http-client/utils/context-extractor.util.js +173 -0
  127. package/http-client/utils/curl-generator.util.d.ts +9 -0
  128. package/http-client/utils/curl-generator.util.js +169 -0
  129. package/http-client/utils/index.d.ts +4 -0
  130. package/http-client/utils/index.js +20 -0
  131. package/http-client/utils/request-id.util.d.ts +4 -0
  132. package/http-client/utils/request-id.util.js +34 -0
  133. package/http-client/utils/retry-recorder.util.d.ts +30 -0
  134. package/http-client/utils/retry-recorder.util.js +143 -0
  135. package/index.d.ts +2 -0
  136. package/index.js +2 -0
  137. package/package.json +1 -1
  138. package/setup/bootstrap.setup.js +5 -1
@@ -0,0 +1,332 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13
+ return new (P || (P = Promise))(function (resolve, reject) {
14
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
16
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
17
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
18
+ });
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.PaymentHttpService = exports.GitHubHttpService = void 0;
22
+ const common_1 = require("@nestjs/common");
23
+ const decorators_1 = require("../decorators");
24
+ const http_client_service_1 = require("../services/http-client.service");
25
+ const cache_options_interface_1 = require("../../cache/interfaces/cache-options.interface");
26
+ let GitHubHttpService = class GitHubHttpService {
27
+ constructor(httpClient) {
28
+ this.httpClient = httpClient;
29
+ }
30
+ getUser(username) {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ return this.httpClient.get(`/users/${username}`);
33
+ });
34
+ }
35
+ searchRepositories(query_1) {
36
+ return __awaiter(this, arguments, void 0, function* (query, sort = 'stars', order = 'desc') {
37
+ return this.httpClient.get('/search/repositories', {
38
+ params: {
39
+ q: query,
40
+ sort,
41
+ order,
42
+ per_page: 20,
43
+ },
44
+ });
45
+ });
46
+ }
47
+ getUserRepositories(username) {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ return this.httpClient.get(`/users/${username}/repos`, {
50
+ params: {
51
+ type: 'owner',
52
+ sort: 'updated',
53
+ per_page: 50,
54
+ },
55
+ });
56
+ });
57
+ }
58
+ createRepository(repoData, token) {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ return this.httpClient.post('/user/repos', repoData, {
61
+ headers: {
62
+ Authorization: `token ${token}`,
63
+ Accept: 'application/vnd.github.v3+json',
64
+ },
65
+ });
66
+ });
67
+ }
68
+ getRepositoryContributors(owner, repo) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ return this.httpClient.get(`/repos/${owner}/${repo}/contributors`);
71
+ });
72
+ }
73
+ getMultipleUsers(usernames) {
74
+ return __awaiter(this, void 0, void 0, function* () {
75
+ const promises = usernames.map((username) => this.getUser(username).catch((error) => {
76
+ console.error(`Failed to get user ${username}:`, error.message);
77
+ return null;
78
+ }));
79
+ return Promise.all(promises);
80
+ });
81
+ }
82
+ getRepositoryDetails(owner, repo, options) {
83
+ return __awaiter(this, void 0, void 0, function* () {
84
+ return this.httpClient.get(`/repos/${owner}/${repo}`);
85
+ });
86
+ }
87
+ };
88
+ exports.GitHubHttpService = GitHubHttpService;
89
+ __decorate([
90
+ (0, decorators_1.HttpRetry)({
91
+ retries: 5,
92
+ retryDelay: (retryCount) => Math.pow(2, retryCount) * 1000,
93
+ retryCondition: (error) => {
94
+ if (!error.response)
95
+ return true;
96
+ const status = error.response.status;
97
+ return status >= 500 || status === 429;
98
+ },
99
+ }),
100
+ (0, decorators_1.HttpCircuitBreaker)({
101
+ failureThreshold: 3,
102
+ recoveryTimeoutMs: 30000,
103
+ }),
104
+ (0, decorators_1.HttpCacheable)({
105
+ ttl: 300000,
106
+ layers: ['cls', 'memory', 'redis'],
107
+ namespace: 'github',
108
+ }),
109
+ (0, decorators_1.HttpLogRequest)({
110
+ databaseLog: true,
111
+ logHeaders: true,
112
+ logBody: false,
113
+ serviceClass: 'GitHubHttpService',
114
+ methodName: 'getUser',
115
+ operationName: 'github.getUser',
116
+ }),
117
+ (0, decorators_1.HttpTimeout)(15000),
118
+ __metadata("design:type", Function),
119
+ __metadata("design:paramtypes", [String]),
120
+ __metadata("design:returntype", Promise)
121
+ ], GitHubHttpService.prototype, "getUser", null);
122
+ __decorate([
123
+ (0, decorators_1.HttpRetry)({ retries: 3 }),
124
+ (0, decorators_1.HttpCacheable)({
125
+ ttl: 600000,
126
+ layers: ['memory', 'redis'],
127
+ namespace: 'github-search',
128
+ condition: (args) => args[0].length > 2,
129
+ }),
130
+ __metadata("design:type", Function),
131
+ __metadata("design:paramtypes", [String, String, String]),
132
+ __metadata("design:returntype", Promise)
133
+ ], GitHubHttpService.prototype, "searchRepositories", null);
134
+ __decorate([
135
+ (0, decorators_1.HttpUseProxy)({
136
+ host: 'proxy.example.com',
137
+ port: 8080,
138
+ protocol: 'http',
139
+ }),
140
+ (0, decorators_1.HttpCacheable)({
141
+ ttl: 120000,
142
+ namespace: 'github-repos',
143
+ }),
144
+ __metadata("design:type", Function),
145
+ __metadata("design:paramtypes", [String]),
146
+ __metadata("design:returntype", Promise)
147
+ ], GitHubHttpService.prototype, "getUserRepositories", null);
148
+ __decorate([
149
+ (0, decorators_1.HttpLogRequest)({
150
+ logHeaders: true,
151
+ logBody: true,
152
+ databaseLog: true,
153
+ sanitizeHeaders: ['authorization', 'x-api-key'],
154
+ }),
155
+ __metadata("design:type", Function),
156
+ __metadata("design:paramtypes", [Object, String]),
157
+ __metadata("design:returntype", Promise)
158
+ ], GitHubHttpService.prototype, "createRepository", null);
159
+ __decorate([
160
+ (0, decorators_1.HttpCircuitBreaker)({
161
+ failureThreshold: 5,
162
+ recoveryTimeoutMs: 60000,
163
+ }),
164
+ (0, decorators_1.HttpCacheable)({
165
+ ttl: 900000,
166
+ namespace: 'github-contributors',
167
+ }),
168
+ __metadata("design:type", Function),
169
+ __metadata("design:paramtypes", [String, String]),
170
+ __metadata("design:returntype", Promise)
171
+ ], GitHubHttpService.prototype, "getRepositoryContributors", null);
172
+ __decorate([
173
+ (0, decorators_1.HttpCacheable)({
174
+ ttl: 120000,
175
+ layers: ['memory'],
176
+ namespace: 'github-repo-details',
177
+ condition: (args) => { var _a; return ((_a = args[2]) === null || _a === void 0 ? void 0 : _a.public) === true; },
178
+ unless: (result, args) => (result === null || result === void 0 ? void 0 : result.archived) === true,
179
+ }),
180
+ __metadata("design:type", Function),
181
+ __metadata("design:paramtypes", [String, String, Object]),
182
+ __metadata("design:returntype", Promise)
183
+ ], GitHubHttpService.prototype, "getRepositoryDetails", null);
184
+ exports.GitHubHttpService = GitHubHttpService = __decorate([
185
+ (0, decorators_1.HttpClient)({
186
+ baseURL: 'https://api.github.com',
187
+ timeout: 10000,
188
+ cache: {
189
+ enabled: true,
190
+ defaultTtl: 300000,
191
+ cacheableMethods: ['GET', 'HEAD'],
192
+ cacheableStatusCodes: [200, 304],
193
+ options: {
194
+ layers: [cache_options_interface_1.CacheLayer.MEMORY, cache_options_interface_1.CacheLayer.REDIS],
195
+ },
196
+ },
197
+ logging: {
198
+ enabled: true,
199
+ logRequests: true,
200
+ logResponses: true,
201
+ logErrors: true,
202
+ logHeaders: true,
203
+ logBody: true,
204
+ maxBodyLength: 1000,
205
+ sanitizeHeaders: ['authorization'],
206
+ logLevel: 'info',
207
+ },
208
+ }),
209
+ (0, common_1.Injectable)(),
210
+ __metadata("design:paramtypes", [http_client_service_1.HttpClientService])
211
+ ], GitHubHttpService);
212
+ let PaymentHttpService = class PaymentHttpService {
213
+ constructor(httpClient) {
214
+ this.httpClient = httpClient;
215
+ }
216
+ createPayment(paymentData, apiKey) {
217
+ return __awaiter(this, void 0, void 0, function* () {
218
+ return this.httpClient.post('/payments', paymentData, {
219
+ headers: {
220
+ Authorization: `Bearer ${apiKey}`,
221
+ 'X-Idempotency-Key': this.generateIdempotencyKey(),
222
+ 'Content-Type': 'application/json',
223
+ },
224
+ });
225
+ });
226
+ }
227
+ getPaymentStatus(paymentId, apiKey) {
228
+ return __awaiter(this, void 0, void 0, function* () {
229
+ return this.httpClient.get(`/payments/${paymentId}`, {
230
+ headers: {
231
+ Authorization: `Bearer ${apiKey}`,
232
+ },
233
+ });
234
+ });
235
+ }
236
+ refundPayment(paymentId, refundData, apiKey) {
237
+ return __awaiter(this, void 0, void 0, function* () {
238
+ return this.httpClient.post(`/payments/${paymentId}/refund`, refundData, {
239
+ headers: {
240
+ Authorization: `Bearer ${apiKey}`,
241
+ 'X-Idempotency-Key': this.generateIdempotencyKey(),
242
+ },
243
+ });
244
+ });
245
+ }
246
+ callExternalApi(url_1) {
247
+ return __awaiter(this, arguments, void 0, function* (url, method = 'GET', data) {
248
+ const { CallStackExtractor } = require('../utils');
249
+ CallStackExtractor.setCallInfo('PaymentHttpService', 'callExternalApi', `payment.${method.toLowerCase()}`);
250
+ try {
251
+ return this.httpClient.request({
252
+ url,
253
+ method,
254
+ data,
255
+ headers: {
256
+ 'Content-Type': 'application/json',
257
+ Authorization: 'Bearer token123',
258
+ },
259
+ });
260
+ }
261
+ finally {
262
+ CallStackExtractor.clearCallInfo();
263
+ }
264
+ });
265
+ }
266
+ generateIdempotencyKey() {
267
+ return `pay_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
268
+ }
269
+ };
270
+ exports.PaymentHttpService = PaymentHttpService;
271
+ __decorate([
272
+ (0, decorators_1.HttpLogRequest)({
273
+ logHeaders: false,
274
+ logBody: false,
275
+ databaseLog: false,
276
+ }),
277
+ (0, decorators_1.HttpTimeout)(10000),
278
+ __metadata("design:type", Function),
279
+ __metadata("design:paramtypes", [Object, String]),
280
+ __metadata("design:returntype", Promise)
281
+ ], PaymentHttpService.prototype, "createPayment", null);
282
+ __decorate([
283
+ (0, decorators_1.HttpCacheable)({
284
+ ttl: 30000,
285
+ layers: ['redis'],
286
+ namespace: 'payment-status',
287
+ }),
288
+ __metadata("design:type", Function),
289
+ __metadata("design:paramtypes", [String, String]),
290
+ __metadata("design:returntype", Promise)
291
+ ], PaymentHttpService.prototype, "getPaymentStatus", null);
292
+ __decorate([
293
+ (0, decorators_1.HttpRetry)({
294
+ retries: 2,
295
+ retryDelay: (retryCount) => retryCount * 2000,
296
+ retryCondition: (error) => {
297
+ if (!error.response)
298
+ return true;
299
+ return error.response.status >= 500;
300
+ },
301
+ }),
302
+ (0, decorators_1.HttpLogRequest)({
303
+ logHeaders: false,
304
+ logBody: false,
305
+ databaseLog: true,
306
+ }),
307
+ __metadata("design:type", Function),
308
+ __metadata("design:paramtypes", [String, Object, String]),
309
+ __metadata("design:returntype", Promise)
310
+ ], PaymentHttpService.prototype, "refundPayment", null);
311
+ exports.PaymentHttpService = PaymentHttpService = __decorate([
312
+ (0, decorators_1.HttpClient)({
313
+ baseURL: 'https://api.payment-provider.com',
314
+ timeout: 15000,
315
+ retry: {
316
+ enabled: false,
317
+ },
318
+ logging: {
319
+ enabled: true,
320
+ logRequests: true,
321
+ logResponses: true,
322
+ logErrors: true,
323
+ logHeaders: false,
324
+ logBody: false,
325
+ maxBodyLength: 1000,
326
+ sanitizeHeaders: ['authorization', 'x-api-key', 'x-client-secret'],
327
+ logLevel: 'info',
328
+ },
329
+ }),
330
+ (0, common_1.Injectable)(),
331
+ __metadata("design:paramtypes", [http_client_service_1.HttpClientService])
332
+ ], PaymentHttpService);
@@ -0,0 +1,17 @@
1
+ import { HttpClientService } from '../services/http-client.service';
2
+ import { HttpLogQueryService } from '../services/http-log-query.service';
3
+ import { HttpReplayService } from '../services/http-replay.service';
4
+ export declare class AuthWithWaitingLockExample {
5
+ private readonly httpClient;
6
+ private readonly logQueryService;
7
+ private readonly replayService;
8
+ private readonly logger;
9
+ constructor(httpClient: HttpClientService, logQueryService: HttpLogQueryService, replayService: HttpReplayService);
10
+ basicAuthWithLock(): Promise<any>;
11
+ batchAuthWithLock(): Promise<any[]>;
12
+ generateCurlFromLogs(): Promise<void>;
13
+ demonstrateRequestReplay(): Promise<void>;
14
+ batchReplayAndCompare(): Promise<void>;
15
+ comprehensiveDemo(): Promise<void>;
16
+ runAllExamples(): Promise<void>;
17
+ }
@@ -0,0 +1,336 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13
+ return new (P || (P = Promise))(function (resolve, reject) {
14
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
16
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
17
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
18
+ });
19
+ };
20
+ var AuthWithWaitingLockExample_1;
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.AuthWithWaitingLockExample = void 0;
23
+ const common_1 = require("@nestjs/common");
24
+ const http_client_service_1 = require("../services/http-client.service");
25
+ const http_log_query_service_1 = require("../services/http-log-query.service");
26
+ const http_replay_service_1 = require("../services/http-replay.service");
27
+ let AuthWithWaitingLockExample = AuthWithWaitingLockExample_1 = class AuthWithWaitingLockExample {
28
+ constructor(httpClient, logQueryService, replayService) {
29
+ this.httpClient = httpClient;
30
+ this.logQueryService = logQueryService;
31
+ this.replayService = replayService;
32
+ this.logger = new common_1.Logger(AuthWithWaitingLockExample_1.name);
33
+ }
34
+ basicAuthWithLock() {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ this.logger.log('=== 示例1: 基本带等待锁的认证请求 ===');
37
+ const requestConfig = {
38
+ method: 'GET',
39
+ url: 'https://api.github.com/user',
40
+ headers: {
41
+ Accept: 'application/vnd.github.v3+json',
42
+ },
43
+ };
44
+ const tokenProvider = () => __awaiter(this, void 0, void 0, function* () {
45
+ this.logger.log('开始获取GitHub访问令牌...');
46
+ yield new Promise((resolve) => setTimeout(resolve, 1000));
47
+ const token = `ghp_${Math.random().toString(36).substring(2, 15)}${Date.now()}`;
48
+ this.logger.log(`成功获取令牌: ${token.substring(0, 20)}...`);
49
+ return token;
50
+ });
51
+ try {
52
+ const response = yield this.httpClient.authRequest(requestConfig, tokenProvider, {
53
+ lockKey: 'github-token-refresh',
54
+ lockTimeout: 30000,
55
+ waitTimeout: 60000,
56
+ enableRetry: true,
57
+ });
58
+ this.logger.log('认证请求成功完成');
59
+ return response;
60
+ }
61
+ catch (error) {
62
+ this.logger.error('认证请求失败', error);
63
+ throw error;
64
+ }
65
+ });
66
+ }
67
+ batchAuthWithLock() {
68
+ return __awaiter(this, void 0, void 0, function* () {
69
+ this.logger.log('=== 示例2: 批量带等待锁的认证请求 ===');
70
+ const requests = [
71
+ {
72
+ config: {
73
+ method: 'GET',
74
+ url: 'https://api.github.com/user/repos',
75
+ },
76
+ key: 'user-repos',
77
+ },
78
+ {
79
+ config: {
80
+ method: 'GET',
81
+ url: 'https://api.github.com/user/starred',
82
+ },
83
+ key: 'user-starred',
84
+ },
85
+ {
86
+ config: {
87
+ method: 'GET',
88
+ url: 'https://api.github.com/user/followers',
89
+ },
90
+ key: 'user-followers',
91
+ },
92
+ ];
93
+ const tokenProvider = () => __awaiter(this, void 0, void 0, function* () {
94
+ this.logger.log('开始获取批量操作的GitHub访问令牌...');
95
+ yield new Promise((resolve) => setTimeout(resolve, 1500));
96
+ const token = `ghp_batch_${Math.random().toString(36).substring(2, 15)}${Date.now()}`;
97
+ this.logger.log(`成功获取批量令牌: ${token.substring(0, 20)}...`);
98
+ return token;
99
+ });
100
+ try {
101
+ const startTime = Date.now();
102
+ const results = yield this.httpClient.authBatchRequest(requests, tokenProvider, {
103
+ lockKey: 'github-batch-token-refresh',
104
+ lockTimeout: 60000,
105
+ waitTimeout: 120000,
106
+ maxConcurrency: 3,
107
+ });
108
+ const endTime = Date.now();
109
+ const duration = endTime - startTime;
110
+ const successful = results.filter((r) => r !== null).length;
111
+ this.logger.log(`
112
+ 批量认证请求完成:
113
+ ┌─────────────────┬──────────┐
114
+ │ 总请求数 │ ${requests.length.toString().padStart(8)} │
115
+ │ 成功请求 │ ${successful.toString().padStart(8)} │
116
+ │ 总耗时 │ ${duration.toString().padStart(8)}ms │
117
+ │ 平均耗时 │ ${(duration / requests.length).toFixed(1).padStart(7)}ms │
118
+ └─────────────────┴──────────┘
119
+ `);
120
+ return results.filter((r) => r !== null);
121
+ }
122
+ catch (error) {
123
+ this.logger.error('批量认证请求失败', error);
124
+ throw error;
125
+ }
126
+ });
127
+ }
128
+ generateCurlFromLogs() {
129
+ return __awaiter(this, void 0, void 0, function* () {
130
+ this.logger.log('=== 示例3: 从HTTP日志生成curl命令 ===');
131
+ try {
132
+ const recentLogs = yield this.logQueryService.findLogs({
133
+ limit: 5,
134
+ sortBy: 'createdAt',
135
+ sortOrder: 'DESC',
136
+ });
137
+ if (recentLogs.logs.length === 0) {
138
+ this.logger.log('没有找到最近的HTTP日志');
139
+ return;
140
+ }
141
+ this.logger.log(`找到 ${recentLogs.logs.length} 条最近的HTTP日志`);
142
+ for (const log of recentLogs.logs) {
143
+ const curlCommand = yield this.logQueryService.generateCurlFromLog(log.id);
144
+ if (curlCommand) {
145
+ this.logger.log(`
146
+ 日志 ${log.id.substring(0, 8)}... 的curl命令:
147
+ ${curlCommand}
148
+ `);
149
+ }
150
+ }
151
+ const batchCurlCommands = yield this.logQueryService.generateBatchCurlCommands({
152
+ limit: 3,
153
+ method: 'GET',
154
+ });
155
+ this.logger.log(`\n批量生成了 ${batchCurlCommands.length} 个curl命令`);
156
+ }
157
+ catch (error) {
158
+ this.logger.error('生成curl命令失败', error);
159
+ }
160
+ });
161
+ }
162
+ demonstrateRequestReplay() {
163
+ return __awaiter(this, void 0, void 0, function* () {
164
+ var _a, _b, _c;
165
+ this.logger.log('=== 示例4: 请求重放功能 ===');
166
+ try {
167
+ const successfulLogs = yield this.logQueryService.findLogs({
168
+ limit: 1,
169
+ success: true,
170
+ method: 'GET',
171
+ sortBy: 'createdAt',
172
+ sortOrder: 'DESC',
173
+ });
174
+ if (successfulLogs.logs.length === 0) {
175
+ this.logger.log('没有找到可重放的请求日志');
176
+ return;
177
+ }
178
+ const logToReplay = successfulLogs.logs[0];
179
+ this.logger.log(`准备重放请求: ${logToReplay.method} ${logToReplay.url}`);
180
+ const replayResult = yield this.replayService.replayByLogId(logToReplay.id, {
181
+ overrideHeaders: false,
182
+ additionalHeaders: {
183
+ 'X-Replay-By': 'http-client-example',
184
+ 'X-Replay-Timestamp': new Date().toISOString(),
185
+ },
186
+ logReplay: true,
187
+ timeout: 30000,
188
+ });
189
+ this.logger.log(`
190
+ 重放结果:
191
+ ┌─────────────────┬──────────┐
192
+ │ 重放ID │ ${replayResult.replayId.substring(0, 20).padStart(8)}... │
193
+ │ 原始状态码 │ ${((_a = logToReplay.statusCode) === null || _a === void 0 ? void 0 : _a.toString().padStart(8)) || 'N/A'} │
194
+ │ 重放状态码 │ ${((_c = (_b = replayResult.response) === null || _b === void 0 ? void 0 : _b.status) === null || _c === void 0 ? void 0 : _c.toString().padStart(8)) || 'N/A'} │
195
+ │ 原始响应时间 │ ${logToReplay.responseTime.toString().padStart(8)}ms │
196
+ │ 重放响应时间 │ ${replayResult.responseTime.toString().padStart(8)}ms │
197
+ │ 重放成功 │ ${replayResult.success ? 'YES'.padStart(8) : 'NO'.padStart(8)} │
198
+ └─────────────────┴──────────┘
199
+ `);
200
+ if (!replayResult.success) {
201
+ this.logger.error(`重放失败: ${replayResult.error}`);
202
+ }
203
+ }
204
+ catch (error) {
205
+ this.logger.error('请求重放失败', error);
206
+ }
207
+ });
208
+ }
209
+ batchReplayAndCompare() {
210
+ return __awaiter(this, void 0, void 0, function* () {
211
+ var _a, _b, _c;
212
+ this.logger.log('=== 示例5: 批量重放和比较 ===');
213
+ try {
214
+ const batchReplayResult = yield this.replayService.batchReplayByQuery({
215
+ method: 'GET',
216
+ limit: 3,
217
+ success: true,
218
+ sortBy: 'createdAt',
219
+ sortOrder: 'DESC',
220
+ }, {
221
+ additionalHeaders: {
222
+ 'X-Batch-Replay': 'true',
223
+ },
224
+ logReplay: true,
225
+ }, 2);
226
+ this.logger.log(`
227
+ 批量重放统计:
228
+ ┌─────────────────┬──────────┐
229
+ │ 总请求数 │ ${batchReplayResult.totalRequests.toString().padStart(8)} │
230
+ │ 成功请求 │ ${batchReplayResult.successfulRequests.toString().padStart(8)} │
231
+ │ 失败请求 │ ${batchReplayResult.failedRequests.toString().padStart(8)} │
232
+ │ 成功率 │ ${batchReplayResult.successRate.toFixed(1).toString().padStart(7)}% │
233
+ │ 总耗时 │ ${batchReplayResult.totalResponseTime.toString().padStart(8)}ms │
234
+ │ 平均响应时间 │ ${batchReplayResult.averageResponseTime.toFixed(1).toString().padStart(7)}ms │
235
+ └─────────────────┴──────────┘
236
+ `);
237
+ for (let i = 0; i < Math.min(batchReplayResult.results.length, 3); i++) {
238
+ const result = batchReplayResult.results[i];
239
+ if (result.originalLog.id) {
240
+ try {
241
+ const comparison = yield this.replayService.replayAndCompare(result.originalLog.id, { logReplay: false });
242
+ this.logger.log(`
243
+ 重放比较 ${i + 1}:
244
+ ┌─────────────────┬──────────┐
245
+ │ 原始状态码 │ ${((_a = comparison.original.statusCode) === null || _a === void 0 ? void 0 : _a.toString().padStart(8)) || 'N/A'} │
246
+ │ 重放状态码 │ ${((_c = (_b = comparison.replay.response) === null || _b === void 0 ? void 0 : _b.status) === null || _c === void 0 ? void 0 : _c.toString().padStart(8)) || 'N/A'} │
247
+ │ 状态匹配 │ ${comparison.comparison.statusMatch ? 'YES'.padStart(8) : 'NO'.padStart(8)} │
248
+ │ 响应时间差异 │ ${comparison.comparison.responseTimeDifference.toString().padStart(8)}ms │
249
+ │ 头部匹配 │ ${comparison.comparison.headersMatch ? 'YES'.padStart(8) : 'NO'.padStart(8)} │
250
+ │ 内容匹配 │ ${comparison.comparison.bodyMatch ? 'YES'.padStart(8) : 'NO'.padStart(8)} │
251
+ └─────────────────┴──────────┘
252
+ `);
253
+ }
254
+ catch (error) {
255
+ this.logger.warn(`无法比较重放结果 ${i + 1}: ${error.message}`);
256
+ }
257
+ }
258
+ }
259
+ }
260
+ catch (error) {
261
+ this.logger.error('批量重放和比较失败', error);
262
+ }
263
+ });
264
+ }
265
+ comprehensiveDemo() {
266
+ return __awaiter(this, void 0, void 0, function* () {
267
+ this.logger.log('=== 示例6: 综合演示 ===');
268
+ try {
269
+ this.logger.log('步骤1: 执行带等待锁的认证请求');
270
+ const authResponse = yield this.basicAuthWithLock();
271
+ this.logger.log('\n步骤2: 查询请求日志');
272
+ const recentLogs = yield this.logQueryService.findLogs({
273
+ limit: 1,
274
+ sortBy: 'createdAt',
275
+ sortOrder: 'DESC',
276
+ });
277
+ if (recentLogs.logs.length > 0) {
278
+ const log = recentLogs.logs[0];
279
+ this.logger.log('\n步骤3: 生成curl命令');
280
+ const curlCommand = yield this.logQueryService.generateCurlFromLog(log.id);
281
+ if (curlCommand) {
282
+ this.logger.log('生成的curl命令:');
283
+ this.logger.log(curlCommand);
284
+ }
285
+ this.logger.log('\n步骤4: 重放请求');
286
+ const replayResult = yield this.replayService.replayByLogId(log.id, {
287
+ additionalHeaders: {
288
+ 'X-Demo-Step': 'replay',
289
+ },
290
+ });
291
+ this.logger.log(`
292
+ 综合演示结果:
293
+ ┌─────────────────┬──────────┐
294
+ │ 原始请求成功 │ ${log.success ? 'YES'.padStart(8) : 'NO'.padStart(8)} │
295
+ │ 重放请求成功 │ ${replayResult.success ? 'YES'.padStart(8) : 'NO'.padStart(8)} │
296
+ │ 原始响应时间 │ ${log.responseTime.toString().padStart(8)}ms │
297
+ │ 重放响应时间 │ ${replayResult.responseTime.toString().padStart(8)}ms │
298
+ └─────────────────┴──────────┘
299
+ `);
300
+ }
301
+ }
302
+ catch (error) {
303
+ this.logger.error('综合演示失败', error);
304
+ }
305
+ });
306
+ }
307
+ runAllExamples() {
308
+ return __awaiter(this, void 0, void 0, function* () {
309
+ this.logger.log('开始运行HTTP客户端等待锁和请求重放示例...\n');
310
+ try {
311
+ yield this.basicAuthWithLock();
312
+ yield new Promise((resolve) => setTimeout(resolve, 1000));
313
+ yield this.batchAuthWithLock();
314
+ yield new Promise((resolve) => setTimeout(resolve, 1000));
315
+ yield this.generateCurlFromLogs();
316
+ yield new Promise((resolve) => setTimeout(resolve, 1000));
317
+ yield this.demonstrateRequestReplay();
318
+ yield new Promise((resolve) => setTimeout(resolve, 1000));
319
+ yield this.batchReplayAndCompare();
320
+ yield new Promise((resolve) => setTimeout(resolve, 1000));
321
+ yield this.comprehensiveDemo();
322
+ this.logger.log('\n所有示例运行完成!');
323
+ }
324
+ catch (error) {
325
+ this.logger.error('示例运行过程中出现错误', error);
326
+ }
327
+ });
328
+ }
329
+ };
330
+ exports.AuthWithWaitingLockExample = AuthWithWaitingLockExample;
331
+ exports.AuthWithWaitingLockExample = AuthWithWaitingLockExample = AuthWithWaitingLockExample_1 = __decorate([
332
+ (0, common_1.Injectable)(),
333
+ __metadata("design:paramtypes", [http_client_service_1.HttpClientService,
334
+ http_log_query_service_1.HttpLogQueryService,
335
+ http_replay_service_1.HttpReplayService])
336
+ ], AuthWithWaitingLockExample);