/
health.ts
67 lines (55 loc) · 1.55 KB
/
health.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Enum value expressing the state of a health check.
*/
export enum HealthStatus { Up = "UP", Down = "DOWN", OutOfService = "OUT_OF_SERVICE" }
export interface Health<P> {
status: HealthStatus;
detail: P;
}
/**
* A HealthIndicator is a function that determines the Health of a sub-system or service this client
* consumes.
*/
export type HealthIndicator = () => Health<any>;
/**
* Register a HealthIndicator at startup.
* @param {HealthIndicator} indicator
*/
export function registerHealthIndicator(indicator: HealthIndicator) {
Indicators.push(indicator);
}
/**
* Returns the combined health of the client.
* @returns {Health<any>}
*/
export function health(): Health<any> {
return CompositeHealthIndicator(Indicators);
}
// public for testing only
export const Indicators: HealthIndicator[] = [];
const CompositeHealthIndicator = (indicators: HealthIndicator[]) => {
if (indicators.length === 1) {
return indicators[0]();
} else if (indicators.length === 0) {
return {
status: HealthStatus.Up,
detail: "Service is up",
};
}
const status: HealthStatus = indicators.map(h => h().status).reduce((p, c) => {
if (p === HealthStatus.Down) {
return p;
}
if (p === HealthStatus.OutOfService && c === HealthStatus.Down) {
return c;
}
if (p === HealthStatus.Up) {
return c;
}
return p;
}, HealthStatus.Up);
return {
status,
detail: indicators.map(i => i()),
};
};