@nathapp/nestjs-health 3.3.0

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 (86) hide show
  1. package/.eslintrc.js +8 -0
  2. package/.nax/features/nestjs-health/.nax-acceptance.test.ts +756 -0
  3. package/.turbo/turbo-build.log +4 -0
  4. package/CHANGELOG.md +15 -0
  5. package/README.md +19 -0
  6. package/dist/constant/health.constants.d.ts +5 -0
  7. package/dist/constant/health.constants.js +9 -0
  8. package/dist/constant/health.constants.js.map +1 -0
  9. package/dist/constant/index.d.ts +1 -0
  10. package/dist/constant/index.js +18 -0
  11. package/dist/constant/index.js.map +1 -0
  12. package/dist/controller/health.controller.d.ts +5 -0
  13. package/dist/controller/health.controller.js +48 -0
  14. package/dist/controller/health.controller.js.map +1 -0
  15. package/dist/controller/index.d.ts +1 -0
  16. package/dist/controller/index.js +18 -0
  17. package/dist/controller/index.js.map +1 -0
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.js +23 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/indicator/cache-health.check.d.ts +20 -0
  22. package/dist/indicator/cache-health.check.js +50 -0
  23. package/dist/indicator/cache-health.check.js.map +1 -0
  24. package/dist/indicator/generic-health.check.d.ts +13 -0
  25. package/dist/indicator/generic-health.check.js +51 -0
  26. package/dist/indicator/generic-health.check.js.map +1 -0
  27. package/dist/indicator/index.d.ts +4 -0
  28. package/dist/indicator/index.js +21 -0
  29. package/dist/indicator/index.js.map +1 -0
  30. package/dist/indicator/prisma-health.check.d.ts +20 -0
  31. package/dist/indicator/prisma-health.check.js +53 -0
  32. package/dist/indicator/prisma-health.check.js.map +1 -0
  33. package/dist/indicator/queue-health.check.d.ts +22 -0
  34. package/dist/indicator/queue-health.check.js +56 -0
  35. package/dist/indicator/queue-health.check.js.map +1 -0
  36. package/dist/interface/health-indicator.interface.d.ts +4 -0
  37. package/dist/interface/health-indicator.interface.js +3 -0
  38. package/dist/interface/health-indicator.interface.js.map +1 -0
  39. package/dist/interface/health-module-options.interface.d.ts +22 -0
  40. package/dist/interface/health-module-options.interface.js +19 -0
  41. package/dist/interface/health-module-options.interface.js.map +1 -0
  42. package/dist/interface/index.d.ts +2 -0
  43. package/dist/interface/index.js +19 -0
  44. package/dist/interface/index.js.map +1 -0
  45. package/dist/module/health.module.d.ts +8 -0
  46. package/dist/module/health.module.js +58 -0
  47. package/dist/module/health.module.js.map +1 -0
  48. package/dist/module/index.d.ts +1 -0
  49. package/dist/module/index.js +18 -0
  50. package/dist/module/index.js.map +1 -0
  51. package/dist/service/health-executor.service.d.ts +20 -0
  52. package/dist/service/health-executor.service.js +50 -0
  53. package/dist/service/health-executor.service.js.map +1 -0
  54. package/dist/service/index.d.ts +1 -0
  55. package/dist/service/index.js +18 -0
  56. package/dist/service/index.js.map +1 -0
  57. package/lib/constant/health.constants.ts +23 -0
  58. package/lib/constant/index.ts +1 -0
  59. package/lib/controller/health.controller.ts +37 -0
  60. package/lib/controller/index.ts +1 -0
  61. package/lib/index.ts +6 -0
  62. package/lib/indicator/cache-health.check.ts +59 -0
  63. package/lib/indicator/generic-health.check.ts +43 -0
  64. package/lib/indicator/index.ts +4 -0
  65. package/lib/indicator/prisma-health.check.ts +59 -0
  66. package/lib/indicator/queue-health.check.ts +72 -0
  67. package/lib/interface/health-indicator.interface.ts +18 -0
  68. package/lib/interface/health-module-options.interface.ts +85 -0
  69. package/lib/interface/index.ts +2 -0
  70. package/lib/module/health.module.ts +62 -0
  71. package/lib/module/index.ts +1 -0
  72. package/lib/service/health-executor.service.ts +69 -0
  73. package/lib/service/index.ts +1 -0
  74. package/package.json +67 -0
  75. package/test/constant/health.constants.spec.ts +34 -0
  76. package/test/controller/health.controller.spec.ts +117 -0
  77. package/test/indicator/cache-health.check.spec.ts +88 -0
  78. package/test/indicator/generic-health.check.spec.ts +61 -0
  79. package/test/indicator/prisma-health.check.spec.ts +69 -0
  80. package/test/indicator/queue-health.check.spec.ts +88 -0
  81. package/test/interface/health-module-options.spec.ts +59 -0
  82. package/test/jest-nax.json +27 -0
  83. package/test/jest-test.json +28 -0
  84. package/test/module/health.module.spec.ts +311 -0
  85. package/test/service/health-executor.service.spec.ts +186 -0
  86. package/tsconfig.json +9 -0
@@ -0,0 +1,62 @@
1
+ import { DynamicModule, Module } from '@nestjs/common';
2
+ import { ConfigurableModuleClass } from '@nathapp/nestjs-common';
3
+ import { TerminusModule } from '@nestjs/terminus';
4
+ import { CacheHealthCheck } from '../indicator/cache-health.check';
5
+ import { GenericHealthCheck } from '../indicator/generic-health.check';
6
+ import { PrismaHealthCheck } from '../indicator/prisma-health.check';
7
+ import { QueueHealthCheck } from '../indicator/queue-health.check';
8
+ import { HealthExecutorService } from '../service/health-executor.service';
9
+ import { createHealthController } from '../controller/health.controller';
10
+ import {
11
+ HEALTH_MODULE_OPTIONS,
12
+ HealthAsyncModuleOptions,
13
+ HealthModuleOptions,
14
+ resolveHealthControllerOptions,
15
+ } from '../interface';
16
+
17
+ const ADAPTERS = [
18
+ CacheHealthCheck,
19
+ PrismaHealthCheck,
20
+ QueueHealthCheck,
21
+ GenericHealthCheck,
22
+ ];
23
+
24
+ function assembleHealthModule(
25
+ baseModule: DynamicModule,
26
+ controllerOptions: HealthModuleOptions['controller'],
27
+ ): DynamicModule {
28
+ const controller = resolveHealthControllerOptions(controllerOptions);
29
+ const controllers =
30
+ controller === false ? [] : [createHealthController(controller)];
31
+
32
+ return {
33
+ ...baseModule,
34
+ global: true,
35
+ module: HealthModule,
36
+ imports: [TerminusModule, ...(baseModule.imports ?? [])],
37
+ controllers,
38
+ providers: [
39
+ ...(baseModule.providers ?? []),
40
+ ...ADAPTERS,
41
+ HealthExecutorService,
42
+ ],
43
+ exports: [HealthExecutorService],
44
+ };
45
+ }
46
+
47
+ @Module({})
48
+ export class HealthModule extends ConfigurableModuleClass<HealthModuleOptions>(
49
+ HEALTH_MODULE_OPTIONS,
50
+ ) {
51
+ static register(options?: HealthModuleOptions): DynamicModule {
52
+ const baseModule = super.register(options ?? {});
53
+ return assembleHealthModule(baseModule, options?.controller);
54
+ }
55
+
56
+ static registerAsync(options: HealthAsyncModuleOptions): DynamicModule {
57
+ const baseModule = (
58
+ super.registerAsync as (o: HealthAsyncModuleOptions) => DynamicModule
59
+ )(options);
60
+ return assembleHealthModule(baseModule, options.controller);
61
+ }
62
+ }
@@ -0,0 +1 @@
1
+ export * from './health.module';
@@ -0,0 +1,69 @@
1
+ import { Inject, Injectable, Type } from '@nestjs/common';
2
+ import { ModuleRef } from '@nestjs/core';
3
+ import { HealthCheckService } from '@nestjs/terminus';
4
+ import { from, Observable } from 'rxjs';
5
+ import {
6
+ HEALTH_MODULE_OPTIONS,
7
+ HealthModuleOptions,
8
+ } from '../interface/health-module-options.interface';
9
+
10
+ /**
11
+ * Minimal contract every probe adapter must satisfy.
12
+ *
13
+ * Adapters own their terminus result key: built-in indicators
14
+ * (`CacheHealthCheck`, `PrismaHealthCheck`, `QueueHealthCheck`,
15
+ * `GenericHealthCheck`) accept an optional `key` argument and fall back to a
16
+ * canonical default (`cache`, `prisma`, `queue`) when called with none. The
17
+ * executor therefore invokes each adapter with **no** key argument and lets
18
+ * the adapter decide how to label its result entry — so callers that wire
19
+ * `CacheHealthCheck` into `readiness` continue to see `result.details.cache`,
20
+ * not `result.details.CacheHealthCheck`.
21
+ *
22
+ * Returned objects follow `@nestjs/terminus`'s `HealthIndicatorResult`
23
+ * shape — a flat key → `{ status, ...details }` map. The executor never
24
+ * inspects the body; it just hands it to terminus via `HealthCheckService`.
25
+ */
26
+ export interface HealthIndicatorLike {
27
+ isHealthy(
28
+ key?: string,
29
+ ): Promise<Record<string, { status: 'up' | 'down' }>> | Record<string, { status: 'up' | 'down' }>;
30
+ }
31
+
32
+ /**
33
+ * Resolves configured adapter **class tokens** through the live Nest injector
34
+ * and composes their `isHealthy()` results via terminus'
35
+ * `HealthCheckService.check()`.
36
+ *
37
+ * Adapter arrays live on `HealthModuleOptions.liveness` and `.readiness`.
38
+ * Empty arrays resolve to `{ status: 'ok' }` (terminus returns OK for `[]`).
39
+ * On error status, terminus throws `ServiceUnavailableException` — the
40
+ * executor surfaces it as an Observable error so Nest's default exception
41
+ * filter renders HTTP 503 on the readiness route.
42
+ */
43
+ @Injectable()
44
+ export class HealthExecutorService {
45
+ constructor(
46
+ private readonly health: HealthCheckService,
47
+ private readonly moduleRef: ModuleRef,
48
+ @Inject(HEALTH_MODULE_OPTIONS)
49
+ private readonly options: HealthModuleOptions,
50
+ ) {}
51
+
52
+ runLiveness(): Observable<import('@nestjs/terminus').HealthCheckResult> {
53
+ return this.run(this.options.liveness ?? []);
54
+ }
55
+
56
+ runReadiness(): Observable<import('@nestjs/terminus').HealthCheckResult> {
57
+ return this.run(this.options.readiness ?? []);
58
+ }
59
+
60
+ private run(
61
+ types: Type<unknown>[],
62
+ ): Observable<import('@nestjs/terminus').HealthCheckResult> {
63
+ const checks = types.map((T) => {
64
+ const inst = this.moduleRef.get<HealthIndicatorLike>(T, { strict: false });
65
+ return () => inst.isHealthy();
66
+ });
67
+ return from(this.health.check(checks));
68
+ }
69
+ }
@@ -0,0 +1 @@
1
+ export * from './health-executor.service';
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@nathapp/nestjs-health",
3
+ "version": "3.3.0",
4
+ "description": "First-party health-check aggregator for NestJS: unifies cache/prisma/queue health behind @nestjs/terminus and exposes liveness/readiness probes",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "clean": "rimraf dist/ .turbo/",
9
+ "build": "rimraf dist && tsc -p tsconfig.json",
10
+ "precommit": "lint-staged",
11
+ "test": "jest --config ./test/jest-test.json",
12
+ "test:cov": "jest --config ./test/jest-test.json --coverage",
13
+ "test:watch": "jest --config ./test/jest-test.json --watch",
14
+ "type-check": "tsc --noEmit -p tsconfig.json",
15
+ "lint": "eslint -c .eslintrc.js",
16
+ "lint:fix": "eslint -c .eslintrc.js --fix"
17
+ },
18
+ "author": "William Khoo",
19
+ "license": "ISC",
20
+ "engines": {
21
+ "node": ">=16"
22
+ },
23
+ "dependencies": {
24
+ "@nestjs/terminus": "^11.0.0"
25
+ },
26
+ "peerDependencies": {
27
+ "@nathapp/nestjs-common": "^3.0.0",
28
+ "@nathapp/nestjs-cache": "^3.0.0",
29
+ "@nathapp/nestjs-prisma": "^3.0.0",
30
+ "@nathapp/nestjs-queue": "^3.0.0",
31
+ "@nestjs/common": "^10.0.0 || ^11.0.0",
32
+ "@nestjs/core": "^10.0.0 || ^11.0.0",
33
+ "rxjs": "^7.0.0"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "@nathapp/nestjs-cache": {
37
+ "optional": true
38
+ },
39
+ "@nathapp/nestjs-prisma": {
40
+ "optional": true
41
+ },
42
+ "@nathapp/nestjs-queue": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "devDependencies": {
47
+ "@nathapp/eslint-config": "1.0.1",
48
+ "@nathapp/nestjs-common": "^3.3.0",
49
+ "@nathapp/typescript-config": "1.0.1",
50
+ "@nestjs/common": "^11.0.0",
51
+ "@nestjs/core": "^11.0.0",
52
+ "@nestjs/platform-express": "^11.0.0",
53
+ "@nestjs/terminus": "^11.0.0",
54
+ "@nestjs/testing": "^11.0.0",
55
+ "@types/jest": "^29.5.2",
56
+ "eslint": "^8.57.0",
57
+ "jest": "^29.5.0",
58
+ "reflect-metadata": "^0.1.13",
59
+ "rxjs": "^7.8.0",
60
+ "supertest": "^7.0.0",
61
+ "ts-jest": "^29.1.0",
62
+ "typescript": "^5"
63
+ },
64
+ "directories": {
65
+ "lib": "lib"
66
+ }
67
+ }
@@ -0,0 +1,34 @@
1
+ import { describe, expect, it } from '@jest/globals';
2
+ import { Test } from '@nestjs/testing';
3
+ import { TerminusModule } from '@nestjs/terminus';
4
+ import {
5
+ CACHE_HEALTH_SOURCE,
6
+ PRISMA_HEALTH_SOURCE,
7
+ QUEUE_HEALTH_SOURCE,
8
+ } from '../../lib';
9
+
10
+ describe('health constants', () => {
11
+ it('CACHE_HEALTH_SOURCE is a truthy Symbol.for token', () => {
12
+ expect(CACHE_HEALTH_SOURCE).toBeTruthy();
13
+ expect(typeof CACHE_HEALTH_SOURCE).toBe('symbol');
14
+ expect(CACHE_HEALTH_SOURCE).toBe(Symbol.for('CACHE_HEALTH_SOURCE'));
15
+ });
16
+
17
+ it('PRISMA_HEALTH_SOURCE is a truthy Symbol.for token', () => {
18
+ expect(PRISMA_HEALTH_SOURCE).toBeTruthy();
19
+ expect(typeof PRISMA_HEALTH_SOURCE).toBe('symbol');
20
+ expect(PRISMA_HEALTH_SOURCE).toBe(Symbol.for('PRISMA_HEALTH_SOURCE'));
21
+ });
22
+
23
+ it('QUEUE_HEALTH_SOURCE is a truthy Symbol.for token', () => {
24
+ expect(QUEUE_HEALTH_SOURCE).toBeTruthy();
25
+ expect(typeof QUEUE_HEALTH_SOURCE).toBe('symbol');
26
+ expect(QUEUE_HEALTH_SOURCE).toBe(Symbol.for('QUEUE_HEALTH_SOURCE'));
27
+ });
28
+
29
+ it('the three source tokens are pairwise distinct', () => {
30
+ expect(CACHE_HEALTH_SOURCE).not.toBe(PRISMA_HEALTH_SOURCE);
31
+ expect(PRISMA_HEALTH_SOURCE).not.toBe(QUEUE_HEALTH_SOURCE);
32
+ expect(CACHE_HEALTH_SOURCE).not.toBe(QUEUE_HEALTH_SOURCE);
33
+ });
34
+ });
@@ -0,0 +1,117 @@
1
+ import { describe, expect, it, beforeAll, afterAll } from '@jest/globals';
2
+ import {
3
+ Injectable,
4
+ INestApplication,
5
+ } from '@nestjs/common';
6
+ import { TerminusModule } from '@nestjs/terminus';
7
+ import { Test } from '@nestjs/testing';
8
+ import * as supertest from 'supertest';
9
+ import {
10
+ createHealthController,
11
+ HEALTH_MODULE_OPTIONS,
12
+ HealthExecutorService,
13
+ } from '../../lib';
14
+
15
+ describe('createHealthController', () => {
16
+ it('AC5: returns a class with controller metadata usable as a NestJS controller', () => {
17
+ const HealthController = createHealthController({
18
+ livenessPath: 'health/live',
19
+ readinessPath: 'health/ready',
20
+ });
21
+
22
+ expect(typeof HealthController).toBe('function');
23
+
24
+ const controllerPath = Reflect.getMetadata('path', HealthController);
25
+ expect(controllerPath).toBeDefined();
26
+
27
+ const handlerNames = Object.getOwnPropertyNames(HealthController.prototype)
28
+ .filter((name) => name !== 'constructor')
29
+ .map((name) => HealthController.prototype[name])
30
+ .filter(
31
+ (fn) => Reflect.getMetadata('method', fn) === 0,
32
+ );
33
+
34
+ expect(handlerNames.length).toBeGreaterThanOrEqual(2);
35
+
36
+ const paths = handlerNames
37
+ .map((fn) => Reflect.getMetadata('path', fn))
38
+ .sort();
39
+ expect(paths).toEqual(['health/live', 'health/ready']);
40
+ });
41
+
42
+ describe('AC6/AC7: mounted in a Nest application with the real HealthExecutorService', () => {
43
+ let upApp: INestApplication;
44
+ let downApp: INestApplication;
45
+
46
+ beforeAll(async () => {
47
+ @Injectable()
48
+ class UpAdapter {
49
+ async isHealthy() {
50
+ return { upSvc: { status: 'up' as const } };
51
+ }
52
+ }
53
+
54
+ const HealthController = createHealthController({
55
+ livenessPath: 'health/live',
56
+ readinessPath: 'health/ready',
57
+ });
58
+
59
+ const upModuleRef = await Test.createTestingModule({
60
+ imports: [TerminusModule],
61
+ controllers: [HealthController],
62
+ providers: [
63
+ HealthExecutorService,
64
+ UpAdapter,
65
+ {
66
+ provide: HEALTH_MODULE_OPTIONS,
67
+ useValue: { liveness: [], readiness: [UpAdapter] },
68
+ },
69
+ ],
70
+ }).compile();
71
+ upApp = upModuleRef.createNestApplication();
72
+ await upApp.init();
73
+
74
+ @Injectable()
75
+ class DownAdapter {
76
+ async isHealthy() {
77
+ return { downSvc: { status: 'down' as const } };
78
+ }
79
+ }
80
+
81
+ const DownHealthController = createHealthController({
82
+ livenessPath: 'health/live',
83
+ readinessPath: 'health/ready',
84
+ });
85
+
86
+ const downModuleRef = await Test.createTestingModule({
87
+ imports: [TerminusModule],
88
+ controllers: [DownHealthController],
89
+ providers: [
90
+ HealthExecutorService,
91
+ DownAdapter,
92
+ {
93
+ provide: HEALTH_MODULE_OPTIONS,
94
+ useValue: { liveness: [], readiness: [DownAdapter] },
95
+ },
96
+ ],
97
+ }).compile();
98
+ downApp = downModuleRef.createNestApplication();
99
+ await downApp.init();
100
+ });
101
+
102
+ afterAll(async () => {
103
+ await upApp?.close();
104
+ await downApp?.close();
105
+ });
106
+
107
+ it('AC6: GET /health/live returns HTTP 200', async () => {
108
+ const res = await supertest(upApp.getHttpServer()).get('/health/live');
109
+ expect(res.status).toBe(200);
110
+ });
111
+
112
+ it('AC7: GET /health/ready returns HTTP 503 when readiness adapter reports down', async () => {
113
+ const res = await supertest(downApp.getHttpServer()).get('/health/ready');
114
+ expect(res.status).toBe(503);
115
+ });
116
+ });
117
+ });
@@ -0,0 +1,88 @@
1
+ import { describe, expect, it } from '@jest/globals';
2
+ import { HealthIndicatorService, TerminusModule } from '@nestjs/terminus';
3
+ import { Test } from '@nestjs/testing';
4
+ import { CACHE_HEALTH_SOURCE, CacheHealthCheck } from '../../lib';
5
+
6
+ describe('CacheHealthCheck', () => {
7
+ it('AC1: is resolvable as an injectable provider from a compiled test module', async () => {
8
+ const moduleRef = await Test.createTestingModule({
9
+ imports: [TerminusModule],
10
+ providers: [CacheHealthCheck],
11
+ }).compile();
12
+
13
+ const instance = moduleRef.get(CacheHealthCheck);
14
+ expect(instance).toBeDefined();
15
+ expect(instance).toBeInstanceOf(CacheHealthCheck);
16
+ await moduleRef.close();
17
+ });
18
+
19
+ it('AC2: with bound source returning healthy=true, isHealthy returns cache entry up', async () => {
20
+ const connections = [{ name: 'redis', status: 'connected' }];
21
+ const source = {
22
+ isHealthy: () => Promise.resolve({ healthy: true, connections }),
23
+ };
24
+ const moduleRef = await Test.createTestingModule({
25
+ imports: [TerminusModule],
26
+ providers: [
27
+ CacheHealthCheck,
28
+ { provide: CACHE_HEALTH_SOURCE, useValue: source },
29
+ ],
30
+ }).compile();
31
+
32
+ const check = moduleRef.get(CacheHealthCheck);
33
+ const result: any = await check.isHealthy('cache');
34
+ expect(result?.cache?.status).toBe('up');
35
+ expect(result?.cache?.connections).toEqual(connections);
36
+ await moduleRef.close();
37
+ });
38
+
39
+ it('AC3: with bound source returning healthy=false, isHealthy returns cache entry down', async () => {
40
+ const connections = [{ name: 'redis', status: 'error' }];
41
+ const source = {
42
+ isHealthy: () => Promise.resolve({ healthy: false, connections }),
43
+ };
44
+ const moduleRef = await Test.createTestingModule({
45
+ imports: [TerminusModule],
46
+ providers: [
47
+ CacheHealthCheck,
48
+ { provide: CACHE_HEALTH_SOURCE, useValue: source },
49
+ ],
50
+ }).compile();
51
+
52
+ const check = moduleRef.get(CacheHealthCheck);
53
+ const result: any = await check.isHealthy('cache');
54
+ expect(result?.cache?.status).toBe('down');
55
+ expect(result?.cache?.connections).toEqual(connections);
56
+ await moduleRef.close();
57
+ });
58
+
59
+ it('AC4: when no cache source token is bound, isHealthy resolves with cache entry down and does not throw', async () => {
60
+ const moduleRef = await Test.createTestingModule({
61
+ imports: [TerminusModule],
62
+ providers: [CacheHealthCheck],
63
+ }).compile();
64
+
65
+ const check = moduleRef.get(CacheHealthCheck);
66
+ await expect(check.isHealthy('cache')).resolves.toBeDefined();
67
+ const result: any = await check.isHealthy('cache');
68
+ expect(result?.cache?.status).toBe('down');
69
+ await moduleRef.close();
70
+ });
71
+
72
+ it('best-effort: when the bound source rejects, isHealthy resolves with cache entry down', async () => {
73
+ const source = { isHealthy: () => Promise.reject(new Error('boom')) };
74
+ const moduleRef = await Test.createTestingModule({
75
+ imports: [TerminusModule],
76
+ providers: [
77
+ CacheHealthCheck,
78
+ { provide: CACHE_HEALTH_SOURCE, useValue: source },
79
+ ],
80
+ }).compile();
81
+
82
+ const check = moduleRef.get(CacheHealthCheck);
83
+ await expect(check.isHealthy('cache')).resolves.toBeDefined();
84
+ const result: any = await check.isHealthy('cache');
85
+ expect(result?.cache?.status).toBe('down');
86
+ await moduleRef.close();
87
+ });
88
+ });
@@ -0,0 +1,61 @@
1
+ import { describe, expect, it } from '@jest/globals';
2
+ import { HealthIndicatorService, TerminusModule } from '@nestjs/terminus';
3
+ import { Test } from '@nestjs/testing';
4
+ import { GenericHealthCheck } from '../../lib';
5
+
6
+ describe('GenericHealthCheck', () => {
7
+ it('is resolvable as an injectable provider from a compiled test module', async () => {
8
+ const moduleRef = await Test.createTestingModule({
9
+ imports: [TerminusModule],
10
+ providers: [GenericHealthCheck],
11
+ }).compile();
12
+
13
+ const instance = moduleRef.get(GenericHealthCheck);
14
+ expect(instance).toBeDefined();
15
+ expect(instance).toBeInstanceOf(GenericHealthCheck);
16
+ await moduleRef.close();
17
+ });
18
+
19
+ it('isHealthy returns svc status up when normalize maps the source result to true', async () => {
20
+ const hi = new HealthIndicatorService();
21
+ const source = { isHealthy: () => Promise.resolve({ status: 'ok' }) };
22
+ const normalize = (r: { status: string }) => r.status === 'ok';
23
+ const check = new GenericHealthCheck(
24
+ hi as any,
25
+ source as any,
26
+ normalize as any,
27
+ );
28
+
29
+ const result: any = await check.isHealthy('svc');
30
+ expect(result?.svc?.status).toBe('up');
31
+ });
32
+
33
+ it('isHealthy returns svc status down when normalize maps the source result to false', async () => {
34
+ const hi = new HealthIndicatorService();
35
+ const source = { isHealthy: () => Promise.resolve({ status: 'degraded' }) };
36
+ const normalize = (r: { status: string }) => r.status !== 'degraded';
37
+ const check = new GenericHealthCheck(
38
+ hi as any,
39
+ source as any,
40
+ normalize as any,
41
+ );
42
+
43
+ const result: any = await check.isHealthy('svc');
44
+ expect(result?.svc?.status).toBe('down');
45
+ });
46
+
47
+ it('isHealthy resolves (does not reject) with svc status down when the source rejects', async () => {
48
+ const hi = new HealthIndicatorService();
49
+ const source = { isHealthy: () => Promise.reject(new Error('boom')) };
50
+ const normalize = (_: unknown) => true;
51
+ const check = new GenericHealthCheck(
52
+ hi as any,
53
+ source as any,
54
+ normalize as any,
55
+ );
56
+
57
+ await expect(check.isHealthy('svc')).resolves.toBeDefined();
58
+ const result: any = await check.isHealthy('svc');
59
+ expect(result?.svc?.status).toBe('down');
60
+ });
61
+ });
@@ -0,0 +1,69 @@
1
+ import { describe, expect, it } from '@jest/globals';
2
+ import { TerminusModule } from '@nestjs/terminus';
3
+ import { Test } from '@nestjs/testing';
4
+ import { PRISMA_HEALTH_SOURCE, PrismaHealthCheck } from '../../lib';
5
+
6
+ describe('PrismaHealthCheck', () => {
7
+ it('AC1: is resolvable as an injectable provider from a compiled test module', async () => {
8
+ const moduleRef = await Test.createTestingModule({
9
+ imports: [TerminusModule],
10
+ providers: [PrismaHealthCheck],
11
+ }).compile();
12
+
13
+ const instance = moduleRef.get(PrismaHealthCheck);
14
+ expect(instance).toBeDefined();
15
+ expect(instance).toBeInstanceOf(PrismaHealthCheck);
16
+ await moduleRef.close();
17
+ });
18
+
19
+ it('AC5: with bound source returning status=up, isHealthy returns prisma entry up; with status=down+message returns down', async () => {
20
+ const upSource = { isHealthy: () => Promise.resolve({ status: 'up' }) };
21
+ const downSource = {
22
+ isHealthy: () => Promise.resolve({ status: 'down', message: 'Not connected' }),
23
+ };
24
+
25
+ const upModule = await Test.createTestingModule({
26
+ imports: [TerminusModule],
27
+ providers: [
28
+ PrismaHealthCheck,
29
+ { provide: PRISMA_HEALTH_SOURCE, useValue: upSource },
30
+ ],
31
+ }).compile();
32
+
33
+ const upCheck = upModule.get(PrismaHealthCheck);
34
+ const upResult: any = await upCheck.isHealthy('prisma');
35
+ expect(upResult?.prisma?.status).toBe('up');
36
+ await upModule.close();
37
+
38
+ const downModule = await Test.createTestingModule({
39
+ imports: [TerminusModule],
40
+ providers: [
41
+ PrismaHealthCheck,
42
+ { provide: PRISMA_HEALTH_SOURCE, useValue: downSource },
43
+ ],
44
+ }).compile();
45
+
46
+ const downCheck = downModule.get(PrismaHealthCheck);
47
+ const downResult: any = await downCheck.isHealthy('prisma');
48
+ expect(downResult?.prisma?.status).toBe('down');
49
+ expect(downResult?.prisma?.message).toBe('Not connected');
50
+ await downModule.close();
51
+ });
52
+
53
+ it('AC6: when the bound source throws, isHealthy resolves with prisma entry down (best-effort)', async () => {
54
+ const source = { isHealthy: () => Promise.reject(new Error('boom')) };
55
+ const moduleRef = await Test.createTestingModule({
56
+ imports: [TerminusModule],
57
+ providers: [
58
+ PrismaHealthCheck,
59
+ { provide: PRISMA_HEALTH_SOURCE, useValue: source },
60
+ ],
61
+ }).compile();
62
+
63
+ const check = moduleRef.get(PrismaHealthCheck);
64
+ await expect(check.isHealthy('prisma')).resolves.toBeDefined();
65
+ const result: any = await check.isHealthy('prisma');
66
+ expect(result?.prisma?.status).toBe('down');
67
+ await moduleRef.close();
68
+ });
69
+ });
@@ -0,0 +1,88 @@
1
+ import { describe, expect, it } from '@jest/globals';
2
+ import { TerminusModule } from '@nestjs/terminus';
3
+ import { Test } from '@nestjs/testing';
4
+ import { QUEUE_HEALTH_SOURCE, QueueHealthCheck } from '../../lib';
5
+
6
+ describe('QueueHealthCheck', () => {
7
+ it('AC1: is resolvable as an injectable provider from a compiled test module', async () => {
8
+ const moduleRef = await Test.createTestingModule({
9
+ imports: [TerminusModule],
10
+ providers: [QueueHealthCheck],
11
+ }).compile();
12
+
13
+ const instance = moduleRef.get(QueueHealthCheck);
14
+ expect(instance).toBeDefined();
15
+ expect(instance).toBeInstanceOf(QueueHealthCheck);
16
+ await moduleRef.close();
17
+ });
18
+
19
+ it('AC7: with bound source returning healthy=true, isHealthy returns queue entry up; with healthy=false returns down', async () => {
20
+ const upConnections = [{ name: 'redis', status: 'connected' }];
21
+ const upSource = {
22
+ isHealthy: () =>
23
+ Promise.resolve({
24
+ healthy: true,
25
+ provider: 'bullmq',
26
+ connections: upConnections,
27
+ latencyMs: 5,
28
+ }),
29
+ };
30
+ const downConnections = [{ name: 'redis', status: 'error' }];
31
+ const downSource = {
32
+ isHealthy: () =>
33
+ Promise.resolve({
34
+ healthy: false,
35
+ provider: 'bullmq',
36
+ connections: downConnections,
37
+ }),
38
+ };
39
+
40
+ const upModule = await Test.createTestingModule({
41
+ imports: [TerminusModule],
42
+ providers: [
43
+ QueueHealthCheck,
44
+ { provide: QUEUE_HEALTH_SOURCE, useValue: upSource },
45
+ ],
46
+ }).compile();
47
+
48
+ const upCheck = upModule.get(QueueHealthCheck);
49
+ const upResult: any = await upCheck.isHealthy('queue');
50
+ expect(upResult?.queue?.status).toBe('up');
51
+ expect(upResult?.queue?.provider).toBe('bullmq');
52
+ expect(upResult?.queue?.connections).toEqual(upConnections);
53
+ expect(upResult?.queue?.latencyMs).toBe(5);
54
+ await upModule.close();
55
+
56
+ const downModule = await Test.createTestingModule({
57
+ imports: [TerminusModule],
58
+ providers: [
59
+ QueueHealthCheck,
60
+ { provide: QUEUE_HEALTH_SOURCE, useValue: downSource },
61
+ ],
62
+ }).compile();
63
+
64
+ const downCheck = downModule.get(QueueHealthCheck);
65
+ const downResult: any = await downCheck.isHealthy('queue');
66
+ expect(downResult?.queue?.status).toBe('down');
67
+ expect(downResult?.queue?.provider).toBe('bullmq');
68
+ expect(downResult?.queue?.connections).toEqual(downConnections);
69
+ await downModule.close();
70
+ });
71
+
72
+ it('best-effort: when the bound source throws, isHealthy resolves with queue entry down', async () => {
73
+ const source = { isHealthy: () => Promise.reject(new Error('boom')) };
74
+ const moduleRef = await Test.createTestingModule({
75
+ imports: [TerminusModule],
76
+ providers: [
77
+ QueueHealthCheck,
78
+ { provide: QUEUE_HEALTH_SOURCE, useValue: source },
79
+ ],
80
+ }).compile();
81
+
82
+ const check = moduleRef.get(QueueHealthCheck);
83
+ await expect(check.isHealthy('queue')).resolves.toBeDefined();
84
+ const result: any = await check.isHealthy('queue');
85
+ expect(result?.queue?.status).toBe('down');
86
+ await moduleRef.close();
87
+ });
88
+ });