From 224971cfabb22e36da7af235042b9b39f96a597a Mon Sep 17 00:00:00 2001
From: Konstantin Tsabolov <konstantin.tsabolov@spherity.com>
Date: Thu, 14 Dec 2023 15:20:38 +0100
Subject: [PATCH] chore(schema-manager): make use of shared health modules and
 response format interceptor

---
 apps/schema-manager/package.json              |  3 --
 apps/schema-manager/src/application.ts        | 17 ++++++-
 .../response-format.interceptor.spec.ts       | 49 -------------------
 .../src/common/response-format.interceptor.ts | 28 -----------
 .../credential-definitions.controller.ts      |  4 +-
 .../src/health/health.controller.ts           | 35 -------------
 .../src/health/health.module.ts               | 34 -------------
 .../src/schemas/schemas.controller.ts         |  4 +-
 8 files changed, 17 insertions(+), 157 deletions(-)
 delete mode 100644 apps/schema-manager/src/common/__tests__/response-format.interceptor.spec.ts
 delete mode 100644 apps/schema-manager/src/common/response-format.interceptor.ts
 delete mode 100644 apps/schema-manager/src/health/health.controller.ts
 delete mode 100644 apps/schema-manager/src/health/health.module.ts

diff --git a/apps/schema-manager/package.json b/apps/schema-manager/package.json
index 7c87d2a..738d493 100644
--- a/apps/schema-manager/package.json
+++ b/apps/schema-manager/package.json
@@ -24,16 +24,13 @@
     "test:e2e": "jest --config ./test/jest.config.js"
   },
   "dependencies": {
-    "@nestjs/axios": "^3.0.1",
     "@nestjs/common": "^10.2.10",
     "@nestjs/config": "^3.1.1",
     "@nestjs/core": "^10.2.10",
     "@nestjs/microservices": "^10.2.10",
     "@nestjs/platform-express": "^10.2.8",
     "@nestjs/swagger": "^7.1.16",
-    "@nestjs/terminus": "^10.1.1",
     "@ocm/shared": "workspace:*",
-    "axios": "^1.6.2",
     "class-transformer": "^0.5.1",
     "class-validator": "^0.14.0",
     "express": "^4.17.3",
diff --git a/apps/schema-manager/src/application.ts b/apps/schema-manager/src/application.ts
index 9b9f46f..75ee18d 100644
--- a/apps/schema-manager/src/application.ts
+++ b/apps/schema-manager/src/application.ts
@@ -4,6 +4,7 @@ import { Module } from '@nestjs/common';
 import { ConfigModule } from '@nestjs/config';
 import { RouterModule } from '@nestjs/core';
 import { ClientsModule, Transport } from '@nestjs/microservices';
+import { HealthModule } from '@ocm/shared';
 
 import { NATS_CLIENT } from './common/constants.js';
 import { httpConfig } from './config/http.config.js';
@@ -11,7 +12,6 @@ import { natsConfig } from './config/nats.config.js';
 import { ssiConfig } from './config/ssi.config.js';
 import { validationSchema } from './config/validation.js';
 import { CredentialDefinitionsModule } from './credential-definitions/credential-definitions.module.js';
-import { HealthModule } from './health/health.module.js';
 import { SchemasModule } from './schemas/schemas.module.js';
 
 @Module({
@@ -44,7 +44,20 @@ import { SchemasModule } from './schemas/schemas.module.js';
       ],
     }),
 
-    HealthModule,
+    HealthModule.registerAsync({
+      inject: [natsConfig.KEY],
+      useFactory: (config: ConfigType<typeof natsConfig>) => {
+        const options: Parameters<typeof HealthModule.register>[0] = {};
+
+        if (config.monitoringUrl) {
+          options.nats = {
+            monitoringUrl: config.monitoringUrl as string,
+          };
+        }
+
+        return options;
+      },
+    }),
 
     SchemasModule,
     CredentialDefinitionsModule,
diff --git a/apps/schema-manager/src/common/__tests__/response-format.interceptor.spec.ts b/apps/schema-manager/src/common/__tests__/response-format.interceptor.spec.ts
deleted file mode 100644
index 4584333..0000000
--- a/apps/schema-manager/src/common/__tests__/response-format.interceptor.spec.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import type { ExecutionContext } from '@nestjs/common';
-import type { TestingModule } from '@nestjs/testing';
-
-import { Test } from '@nestjs/testing';
-import { of } from 'rxjs';
-
-import { ResponseFormatInterceptor } from '../response-format.interceptor.js';
-
-describe('ResponseFormatInterceptor', () => {
-  let interceptor: ResponseFormatInterceptor;
-
-  beforeEach(async () => {
-    const module: TestingModule = await Test.createTestingModule({
-      providers: [ResponseFormatInterceptor],
-    }).compile();
-
-    interceptor = module.get<ResponseFormatInterceptor>(
-      ResponseFormatInterceptor,
-    );
-  });
-
-  it('should be defined', () => {
-    expect(interceptor).toBeDefined();
-    expect(interceptor).toBeInstanceOf(ResponseFormatInterceptor);
-  });
-
-  it('should intercept the request and format the response', (done) => {
-    const context: ExecutionContext = {
-      switchToHttp: () => ({
-        getResponse: () => ({
-          statusCode: 200,
-        }),
-      }),
-    } as ExecutionContext;
-    const next = {
-      handle: jest.fn().mockReturnValue(of('Hello World')),
-    };
-
-    const result = interceptor.intercept(context, next);
-
-    expect(result).toBeDefined();
-    expect(next.handle).toHaveBeenCalled();
-
-    result.subscribe((response) => {
-      expect(response).toEqual({ statusCode: 200, data: 'Hello World' });
-      done();
-    });
-  });
-});
diff --git a/apps/schema-manager/src/common/response-format.interceptor.ts b/apps/schema-manager/src/common/response-format.interceptor.ts
deleted file mode 100644
index 9d85a0e..0000000
--- a/apps/schema-manager/src/common/response-format.interceptor.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import type {
-  CallHandler,
-  ExecutionContext,
-  NestInterceptor,
-} from '@nestjs/common';
-
-import { Injectable } from '@nestjs/common';
-import { map, type Observable } from 'rxjs';
-
-@Injectable()
-export class ResponseFormatInterceptor implements NestInterceptor {
-  public intercept(
-    context: ExecutionContext,
-    next: CallHandler,
-  ): Observable<unknown> {
-    const ctx = context.switchToHttp();
-    const response = ctx.getResponse();
-
-    return next.handle().pipe(
-      map((data) => {
-        return {
-          statusCode: response.statusCode,
-          data,
-        };
-      }),
-    );
-  }
-}
diff --git a/apps/schema-manager/src/credential-definitions/credential-definitions.controller.ts b/apps/schema-manager/src/credential-definitions/credential-definitions.controller.ts
index 099cb60..f301b4e 100644
--- a/apps/schema-manager/src/credential-definitions/credential-definitions.controller.ts
+++ b/apps/schema-manager/src/credential-definitions/credential-definitions.controller.ts
@@ -11,9 +11,7 @@ import {
   ValidationPipe,
 } from '@nestjs/common';
 import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
-import { MultitenancyParams } from '@ocm/shared';
-
-import { ResponseFormatInterceptor } from '../common/response-format.interceptor.js';
+import { MultitenancyParams, ResponseFormatInterceptor } from '@ocm/shared';
 
 import { CredentialDefinitionsService } from './credential-definitions.service.js';
 import { CreateCredentialDefinitionPayload } from './dto/create-credential-definition.dto.js';
diff --git a/apps/schema-manager/src/health/health.controller.ts b/apps/schema-manager/src/health/health.controller.ts
deleted file mode 100644
index 70092f2..0000000
--- a/apps/schema-manager/src/health/health.controller.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { HealthIndicatorFunction } from '@nestjs/terminus';
-
-import { Controller, Get } from '@nestjs/common';
-import { ConfigService } from '@nestjs/config';
-import {
-  HealthCheck,
-  HealthCheckService,
-  HttpHealthIndicator,
-} from '@nestjs/terminus';
-
-@Controller()
-export class HealthController {
-  public constructor(
-    private readonly config: ConfigService,
-    private readonly health: HealthCheckService,
-    private readonly http: HttpHealthIndicator,
-  ) {}
-
-  @Get()
-  @HealthCheck()
-  public check() {
-    const healthIndicators: HealthIndicatorFunction[] = [];
-
-    const natsMonitoringUrl = this.config.get('nats.monitoringUrl');
-    if (typeof natsMonitoringUrl === 'string') {
-      healthIndicators.push(() =>
-        this.http.pingCheck('nats', natsMonitoringUrl),
-      );
-    } else {
-      healthIndicators.push(() => ({ nats: { status: 'down' } }));
-    }
-
-    return this.health.check(healthIndicators);
-  }
-}
diff --git a/apps/schema-manager/src/health/health.module.ts b/apps/schema-manager/src/health/health.module.ts
deleted file mode 100644
index 17ccd14..0000000
--- a/apps/schema-manager/src/health/health.module.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { ConfigType } from '@nestjs/config';
-
-import { HttpModule } from '@nestjs/axios';
-import { Module } from '@nestjs/common';
-import { ClientsModule, Transport } from '@nestjs/microservices';
-import { TerminusModule } from '@nestjs/terminus';
-
-import { SERVICE_NAME } from '../common/constants.js';
-import { natsConfig } from '../config/nats.config.js';
-
-import { HealthController } from './health.controller.js';
-
-@Module({
-  imports: [
-    TerminusModule,
-    HttpModule,
-    ClientsModule.registerAsync({
-      clients: [
-        {
-          name: SERVICE_NAME,
-          inject: [natsConfig.KEY],
-          useFactory: (config: ConfigType<typeof natsConfig>) => ({
-            transport: Transport.NATS,
-            options: {
-              servers: [config.url as string],
-            },
-          }),
-        },
-      ],
-    }),
-  ],
-  controllers: [HealthController],
-})
-export class HealthModule {}
diff --git a/apps/schema-manager/src/schemas/schemas.controller.ts b/apps/schema-manager/src/schemas/schemas.controller.ts
index 2436a2a..8646067 100644
--- a/apps/schema-manager/src/schemas/schemas.controller.ts
+++ b/apps/schema-manager/src/schemas/schemas.controller.ts
@@ -19,11 +19,9 @@ import {
   Version,
 } from '@nestjs/common';
 import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
-import { MultitenancyParams } from '@ocm/shared';
+import { MultitenancyParams, ResponseFormatInterceptor } from '@ocm/shared';
 import { Observable, of, switchMap } from 'rxjs';
 
-import { ResponseFormatInterceptor } from '../common/response-format.interceptor.js';
-
 import { GetByIdParams } from './dto/get-by-id.dto.js';
 import { RegisterSchemaPayload } from './dto/register-schema.dto.js';
 import { SchemasService } from './schemas.service.js';
-- 
GitLab