nest-monitor 0.3.2 → 0.3.4

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.
@@ -1,5 +1,4 @@
1
1
  /**
2
- * Помечает GET-эндпоинт для автоматического тестирования.
3
- * @param path Относительный путь к эндпоинту (например, '/health')
2
+ * Помечает весь контроллер для автоматического тестирования всех GET-эндпоинтов.
4
3
  */
5
- export declare const AutoTest: (path: string) => MethodDecorator;
4
+ export declare const AutoTest: () => ClassDecorator;
@@ -4,13 +4,9 @@ exports.AutoTest = void 0;
4
4
  const common_1 = require("@nestjs/common");
5
5
  const auto_test_constants_1 = require("./auto-test.constants");
6
6
  /**
7
- * Помечает GET-эндпоинт для автоматического тестирования.
8
- * @param path Относительный путь к эндпоинту (например, '/health')
7
+ * Помечает весь контроллер для автоматического тестирования всех GET-эндпоинтов.
9
8
  */
10
- const AutoTest = (path) => {
11
- return (0, common_1.SetMetadata)(auto_test_constants_1.AUTO_TEST_METADATA, {
12
- path,
13
- method: 'GET',
14
- });
9
+ const AutoTest = () => {
10
+ return (0, common_1.SetMetadata)(auto_test_constants_1.AUTO_TEST_METADATA, true);
15
11
  };
16
12
  exports.AutoTest = AutoTest;
@@ -7,4 +7,5 @@ export declare class AutoTestModule implements OnModuleInit {
7
7
  private readonly reflector;
8
8
  constructor(discoveryService: DiscoveryService, autoTestService: AutoTestService, reflector: Reflector);
9
9
  onModuleInit(): void;
10
+ private extractGetEndpoints;
10
11
  }
@@ -23,18 +23,29 @@ let AutoTestModule = class AutoTestModule {
23
23
  }
24
24
  onModuleInit() {
25
25
  const controllers = this.discoveryService.getControllers();
26
- for (const controller of controllers) {
27
- const instance = controller.instance;
28
- const prototype = Object.getPrototypeOf(instance);
29
- const methodNames = Object.getOwnPropertyNames(prototype).filter((name) => name !== 'constructor' && typeof prototype[name] === 'function');
30
- for (const methodName of methodNames) {
31
- const methodRef = prototype[methodName];
32
- const metadata = this.reflector.get(auto_test_constants_1.AUTO_TEST_METADATA, methodRef);
33
- if (metadata && metadata.method === 'GET' && metadata.path) {
34
- this.autoTestService.registerEndpoint(metadata, controller.metatype, methodName);
35
- }
26
+ for (const wrapper of controllers) {
27
+ const metatype = wrapper.metatype;
28
+ const shouldAutoTest = this.reflector.get(auto_test_constants_1.AUTO_TEST_METADATA, metatype);
29
+ if (!shouldAutoTest)
30
+ continue;
31
+ const endpoints = this.extractGetEndpoints(metatype);
32
+ const controllerName = metatype.name || 'UnknownController';
33
+ this.autoTestService.registerControllerEndpoints(controllerName, endpoints);
34
+ }
35
+ }
36
+ extractGetEndpoints(metatype) {
37
+ const endpoints = [];
38
+ const prototype = Object.getPrototypeOf(metatype.prototype);
39
+ const methodNames = Object.getOwnPropertyNames(prototype).filter((name) => name !== 'constructor' && typeof prototype[name] === 'function');
40
+ for (const methodName of methodNames) {
41
+ const methodRef = prototype[methodName];
42
+ const routePath = Reflect.getMetadata('path', methodRef);
43
+ const requestMethod = Reflect.getMetadata('method', methodRef);
44
+ if (routePath !== undefined && requestMethod === 0) {
45
+ endpoints.push({ path: routePath, methodName });
36
46
  }
37
47
  }
48
+ return endpoints;
38
49
  }
39
50
  };
40
51
  exports.AutoTestModule = AutoTestModule;
@@ -1,12 +1,10 @@
1
1
  import { HttpService } from '@nestjs/axios';
2
2
  import { OnApplicationBootstrap } from '@nestjs/common';
3
- import { Reflector } from '@nestjs/core';
4
- import { IAutoTestMetadata } from '../interfaces/auto-test-metadata.interface';
3
+ import { IAutoTestEndpoint } from '../interfaces/auto-test-endpoint.interface';
5
4
  export declare class AutoTestService implements OnApplicationBootstrap {
6
5
  private readonly httpService;
7
- private readonly reflector;
8
6
  private endpoints;
9
- constructor(httpService: HttpService, reflector: Reflector);
10
- registerEndpoint(metadata: IAutoTestMetadata, controller: unknown, methodName: string): void;
7
+ constructor(httpService: HttpService);
8
+ registerControllerEndpoints(controllerName: string, endpoints: IAutoTestEndpoint[]): void;
11
9
  onApplicationBootstrap(): Promise<void>;
12
10
  }
@@ -12,52 +12,50 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.AutoTestService = void 0;
13
13
  const axios_1 = require("@nestjs/axios");
14
14
  const common_1 = require("@nestjs/common");
15
- const core_1 = require("@nestjs/core");
16
15
  const rxjs_1 = require("rxjs");
17
16
  let AutoTestService = class AutoTestService {
18
- constructor(httpService, reflector) {
17
+ constructor(httpService) {
19
18
  this.httpService = httpService;
20
- this.reflector = reflector;
21
19
  this.endpoints = [];
22
20
  }
23
- registerEndpoint(metadata, controller, methodName) {
24
- this.endpoints.push({
25
- ...metadata,
26
- controller,
27
- methodName,
28
- });
21
+ registerControllerEndpoints(controllerName, endpoints) {
22
+ if (endpoints.length > 0) {
23
+ this.endpoints.push({ controllerName, endpoints });
24
+ }
29
25
  }
30
26
  async onApplicationBootstrap() {
31
27
  if (this.endpoints.length === 0) {
32
- console.log('[AutoTest] Нет эндпоинтов для автоматического тестирования.');
28
+ console.log('[AutoTest] Нет контроллеров для автоматического тестирования.');
33
29
  return;
34
30
  }
35
- console.log(`\n[AutoTest] Запуск автоматических тестов для ${this.endpoints.length} GET-эндпоинтов...\n`);
31
+ console.log(`\n[AutoTest] Запуск тестов для ${this.endpoints.length} контроллеров...\n`);
36
32
  const host = process.env.HOST || '127.0.0.1';
37
33
  const port = process.env.PORT || '3000';
38
34
  const baseUrl = `http://${host}:${port}`;
39
- for (const endpoint of this.endpoints) {
40
- const url = `${baseUrl}${endpoint.path}`;
41
- const start = Date.now();
42
- try {
43
- console.log(`[AutoTest] Тестирую: GET ${url}`);
44
- const response = await (0, rxjs_1.firstValueFrom)(this.httpService.get(url));
45
- const duration = Date.now() - start;
46
- console.log(`✅ [AutoTest] УСПЕХ: ${url} статус ${response.status} (${duration}мс)`);
47
- }
48
- catch (error) {
49
- const duration = Date.now() - start;
50
- const status = error.response?.status || '???';
51
- const message = error.message || 'Неизвестная ошибка';
52
- console.error(`❌ [AutoTest] ОШИБКА: ${url} → статус ${status} (${duration}мс) — ${message}`);
35
+ for (const { controllerName, endpoints } of this.endpoints) {
36
+ console.log(`\n🔍 [AutoTest] Контроллер: ${controllerName}`);
37
+ for (const endpoint of endpoints) {
38
+ const url = `${baseUrl}${endpoint.path}`;
39
+ const start = Date.now();
40
+ try {
41
+ console.log(` → Тестирую: GET ${url}`);
42
+ const response = await (0, rxjs_1.firstValueFrom)(this.httpService.get(url));
43
+ const duration = Date.now() - start;
44
+ console.log(` ✅ УСПЕХ: статус ${response.status} (${duration}мс)`);
45
+ }
46
+ catch (error) {
47
+ const duration = Date.now() - start;
48
+ const status = error.response?.status || '???';
49
+ const message = error.message || 'Неизвестная ошибка';
50
+ console.error(` ❌ ОШИБКА: статус ${status} (${duration}мс) — ${message}`);
51
+ }
53
52
  }
54
53
  }
55
- console.log('[AutoTest] Автоматическое тестирование завершено.\n');
54
+ console.log('\n[AutoTest] Автоматическое тестирование завершено.\n');
56
55
  }
57
56
  };
58
57
  exports.AutoTestService = AutoTestService;
59
58
  exports.AutoTestService = AutoTestService = __decorate([
60
59
  (0, common_1.Injectable)(),
61
- __metadata("design:paramtypes", [axios_1.HttpService,
62
- core_1.Reflector])
60
+ __metadata("design:paramtypes", [axios_1.HttpService])
63
61
  ], AutoTestService);
@@ -0,0 +1,4 @@
1
+ export interface IAutoTestEndpoint {
2
+ path: string;
3
+ methodName: string;
4
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nest-monitor",
3
3
  "type": "commonjs",
4
- "version": "0.3.2",
4
+ "version": "0.3.4",
5
5
  "description": "Библиотека для сбора метрик с высоконагруженного приложения на Nest.js",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -52,7 +52,7 @@
52
52
  "typescript-eslint": "^8.46.0"
53
53
  },
54
54
  "peerDependencies": {
55
- "@nestjs/axios": "^4.0.1",
55
+ "@nestjs/axios": "^3.0.1",
56
56
  "@nestjs/common": "^9.0.0 || ^10.0.0",
57
57
  "@nestjs/core": "^9.0.0 || ^10.0.0",
58
58
  "rxjs": "^7.8.0 || ^8.0.0"
@@ -1,6 +0,0 @@
1
- export interface IAutoTestMetadata {
2
- path: string;
3
- method: 'GET';
4
- controller: unknown;
5
- methodName: string;
6
- }