import { Autowired, Component, getTargetClass } from '@celljs/core'; import { HealthNotFoundError } from './health-errors'; import { CompositeHealth, HealthComponent, HealthExecutor, HealthIndicator, HealthStatusAggregator } from './health-protocol'; @Component(HealthExecutor) export class HealthExecutorImpl implements HealthExecutor { @Autowired(HealthIndicator) protected readonly healthIndicators: HealthIndicator[]; @Autowired(HealthStatusAggregator) protected readonly healthStatusAggregator: HealthStatusAggregator; protected getHealthIndicatorName(healthIndicator: HealthIndicator): string | undefined { return getTargetClass(healthIndicator)?.name?.toLowerCase(); } async execute(indicatorName?: string): Promise { if (indicatorName) { const healthIndicator = this.healthIndicators.find(h => { const name = this.getHealthIndicatorName(h); return name?.startsWith(indicatorName); }); if (healthIndicator) { return healthIndicator.health(); } throw new HealthNotFoundError(indicatorName, `Health indicator ${indicatorName} not found`); } // Each indicator is checked once, all at the same time; the components keep the order of the indicators. const named = this.healthIndicators .map(indicator => ({ indicator, name: this.getHealthIndicatorName(indicator) })) .filter((entry): entry is { indicator: HealthIndicator, name: string } => !!entry.name); const healths = await Promise.all(named.map(({ indicator }) => indicator.health())); const components: { [key: string]: HealthComponent } = {}; named.forEach(({ name }, index) => { components[name.replace('healthindicator', '')] = healths[index]; }); return { status: this.healthStatusAggregator.aggregate(Object.values(components).map(c => c.status)), components }; } }