/** * CheckApiHealthUseCase * * Executes health checks and returns status. * This Use Case orchestrates the health check process and emits events. */ import { HealthCheckQuery, HealthCheckResult } from '../ports/HealthCheckQuery'; import { HealthEventPublisher } from '../ports/HealthEventPublisher'; export interface CheckApiHealthUseCasePorts { healthCheckAdapter: HealthCheckQuery; eventPublisher: HealthEventPublisher; } export class CheckApiHealthUseCase { constructor(private readonly ports: CheckApiHealthUseCasePorts) {} /** * Execute a health check */ async execute(): Promise { const { healthCheckAdapter, eventPublisher } = this.ports; try { // Perform the health check const result = await healthCheckAdapter.performHealthCheck(); // Emit appropriate event based on result if (result.healthy) { await eventPublisher.publishHealthCheckCompleted({ healthy: result.healthy, responseTime: result.responseTime, timestamp: result.timestamp, }); } else { const error = result.error || 'Unknown error'; await eventPublisher.publishHealthCheckFailed({ error, timestamp: result.timestamp, }); // Return result with error property return { ...result, error, }; } return result; } catch (error) { const errorMessage = error instanceof Error ? error.message : (error ? String(error) : 'Unknown error'); const timestamp = new Date(); // Emit failed event await eventPublisher.publishHealthCheckFailed({ error: errorMessage, timestamp, }); return { healthy: false, responseTime: 0, error: errorMessage, timestamp, }; } } }