Skip to content
Open

Next #2678

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions lib/health-check/health-check-executor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
} from './health-check-result.interface';
import { type HealthCheckError } from '../health-check/health-check.error';
import {
type InferHealthIndicatorResults,
type HealthIndicatorFunction,
type HealthIndicatorResult,
} from '../health-indicator';
Expand Down Expand Up @@ -37,13 +38,15 @@ export class HealthCheckExecutor implements BeforeApplicationShutdown {
* @returns the result of given health indicators
* @param healthIndicators The health indicators which should get executed
*/
async execute(
healthIndicators: HealthIndicatorFunction[],
): Promise<HealthCheckResult> {
async execute<const TFns extends HealthIndicatorFunction[]>(
healthIndicators: TFns,
) {
const { results, errors } =
await this.executeHealthIndicators(healthIndicators);

return this.getResult(results, errors);
return this.getResult(results, errors) as HealthCheckResult<
InferHealthIndicatorResults<TFns>
>;
}

/**
Expand Down
18 changes: 13 additions & 5 deletions lib/health-check/health-check-result.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ export type HealthCheckStatus = 'error' | 'ok' | 'shutting_down';
* The result of a health check
* @publicApi
*/
export interface HealthCheckResult {
export type HealthCheckResult<
TDetails extends HealthIndicatorResult = HealthIndicatorResult,
TInfo extends Partial<HealthIndicatorResult> | undefined =
| Partial<TDetails>
| undefined,
TError extends Partial<HealthIndicatorResult> | undefined =
| Partial<TDetails>
| undefined,
> = {
/**
* The overall status of the Health Check
*/
Expand All @@ -18,14 +26,14 @@ export interface HealthCheckResult {
* The info object contains information of each health indicator
* which is of status "up"
*/
info?: HealthIndicatorResult;
info?: TInfo;
/**
* The error object contains information of each health indicator
* which is of status "down"
*/
error?: HealthIndicatorResult;
error?: TError;
/**
* The details object contains information of every health indicator.
*/
details: HealthIndicatorResult;
}
details: TDetails;
};
39 changes: 24 additions & 15 deletions lib/health-check/health-check.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import {
Inject,
ConsoleLogger,
LoggerService,
InternalServerErrorException,
} from '@nestjs/common';
import { ErrorLogger } from './error-logger/error-logger.interface';
import { ERROR_LOGGER } from './error-logger/error-logger.provider';
import { HealthCheckExecutor } from './health-check-executor.service';
import { type HealthCheckResult } from './health-check-result.interface';
import { type HealthIndicatorFunction } from '../health-indicator';
import { TERMINUS_LOGGER } from './logger/logger.provider';

Expand Down Expand Up @@ -43,22 +43,31 @@ export class HealthCheckService {
* ```
* @param healthIndicators The health indicators which should be checked
*/
async check(
healthIndicators: HealthIndicatorFunction[],
): Promise<HealthCheckResult> {
async check<const TFns extends HealthIndicatorFunction[]>(
healthIndicators: TFns,
) {
const result = await this.healthCheckExecutor.execute(healthIndicators);
if (result.status === 'ok') {
return result;
}

if (result.status === 'error') {
const msg = this.errorLogger.getErrorMessage(
'Health Check has failed!',
result.details,
);
this.logger.error(msg);
}
switch (result.status) {
case 'ok':
return result;

throw new ServiceUnavailableException(result);
case 'error':
const msg = this.errorLogger.getErrorMessage(
'Health Check has failed!',
result.details,
);
this.logger.error(msg);
throw new ServiceUnavailableException(result);

case 'shutting_down':
throw new ServiceUnavailableException(result);

default:
// Ensure that we have exhaustively checked all cases
// eslint-disable-next-line unused-imports/no-unused-vars
const exhaustiveCheck: never = result.status;
throw new InternalServerErrorException();
}
}
}
23 changes: 23 additions & 0 deletions lib/health-indicator/health-indicator-result.interface.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { type HealthIndicatorFunction } from './health-indicator';

/**
* @publicApi
*/
Expand All @@ -12,3 +14,24 @@ export type HealthIndicatorResult<
Status extends HealthIndicatorStatus = HealthIndicatorStatus,
OptionalData extends Record<string, any> = Record<string, any>,
> = Record<Key, { status: Status } & OptionalData>;

/**
* @internal
*/
export type InferHealthIndicatorResult<
Fn extends HealthIndicatorFunction = HealthIndicatorFunction,
> = Awaited<ReturnType<Fn>>;

/**
* @internal
*/
export type InferHealthIndicatorResults<
Fns extends readonly HealthIndicatorFunction[] = HealthIndicatorFunction[],
R extends readonly any[] = [],
> = Fns extends readonly [
infer Fn extends HealthIndicatorFunction,
...infer Rest extends readonly HealthIndicatorFunction[],
]
? InferHealthIndicatorResults<Rest, [...R, Fn]> &
InferHealthIndicatorResult<Fn>
: HealthIndicatorResult;
6 changes: 3 additions & 3 deletions lib/health-indicator/health-indicator.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ export class HealthIndicatorSession<Key extends Readonly<string> = string> {
*/
down<T extends AdditionalData>(
data?: T,
): HealthIndicatorResult<typeof this.key, 'down', T>;
): HealthIndicatorResult<Key, 'down', T>;
down<T extends string>(
data?: T,
): HealthIndicatorResult<typeof this.key, 'down', { message: T }>;
): HealthIndicatorResult<Key, 'down', { message: T }>;
down<T extends AdditionalData | string>(
data?: T,
): HealthIndicatorResult<typeof this.key, 'down'> {
): HealthIndicatorResult<Key, 'down'> {
let additionalData: AdditionalData = {};

if (typeof data === 'string') {
Expand Down
6 changes: 5 additions & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
export { TerminusModule } from './terminus.module';
export { TerminusModuleOptions } from './terminus-options.interface';
export {
TerminusModuleOptions,
TerminusModuleAsyncOptions,
TerminusModuleOptionsFactory,
} from './terminus-options.interface';
export * from './health-indicator';
export * from './errors';
export {
Expand Down
42 changes: 41 additions & 1 deletion lib/terminus-options.interface.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { type LoggerService, type Type } from '@nestjs/common';
import {
type LoggerService,
type ModuleMetadata,
type Type,
} from '@nestjs/common';

export type ErrorLogStyle = 'pretty' | 'json';

Expand Down Expand Up @@ -26,3 +30,39 @@ export interface TerminusModuleOptions {
*/
gracefulShutdownTimeoutMs?: number;
}

/**
* Options factory interface for creating TerminusModuleOptions
* @publicApi
*/
export interface TerminusModuleOptionsFactory {
createTerminusOptions():
| Promise<TerminusModuleOptions>
| TerminusModuleOptions;
}

/**
* Async options for TerminusModule
* @publicApi
*/
export interface TerminusModuleAsyncOptions
extends Pick<ModuleMetadata, 'imports'> {
/**
* Factory function that returns TerminusModuleOptions
*/
useFactory?: (
...args: any[]
) => Promise<TerminusModuleOptions> | TerminusModuleOptions;
/**
* Dependencies to inject into the factory function
*/
inject?: any[];
/**
* Class to use as options factory
*/
useClass?: Type<TerminusModuleOptionsFactory>;
/**
* Existing instance to use as options factory
*/
useExisting?: Type<TerminusModuleOptionsFactory>;
}
6 changes: 6 additions & 0 deletions lib/terminus.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,9 @@
* @internal
*/
export const CHECK_DISK_SPACE_LIB = 'CheckDiskSpaceLib';

/**
* The inject token for the TerminusModuleOptions
* @internal
*/
export const TERMINUS_MODULE_OPTIONS = 'TERMINUS_MODULE_OPTIONS';
Loading