UNPKG

thrilled-be-core

Version:

Core Express backend package with middleware, logging, security, and base application setup

103 lines (102 loc) 3.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HealthCheckManager = void 0; const Logger_1 = require("../logging/Logger"); class HealthCheckManager { checks = new Map(); logger; config; constructor(config = {}, logger) { this.config = { enabled: true, endpoint: '/health', timeout: 5000, checks: {}, interval: 0, ...config, }; this.logger = logger || Logger_1.Logger.create({ level: 'info' }); } /** * Register a health check */ register(check) { this.checks.set(check.name, check); this.logger.debug(`Health check registered: ${check.name}`); } /** * Remove a health check */ unregister(name) { if (this.checks.delete(name)) { this.logger.debug(`Health check unregistered: ${name}`); } } /** * Run all health checks */ async runChecks() { const results = {}; let overallStatus = 'healthy'; const checkPromises = Array.from(this.checks.entries()).map(async ([name, check]) => { try { const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Health check timeout')), this.config.timeout)); const result = await Promise.race([check.check(), timeoutPromise]); results[name] = result; if (result.status === 'unhealthy') { overallStatus = 'unhealthy'; } } catch (error) { results[name] = { status: 'unhealthy', message: error.message, }; overallStatus = 'unhealthy'; } }); await Promise.all(checkPromises); return { status: overallStatus, checks: results, timestamp: new Date().toISOString(), uptime: process.uptime(), }; } /** * Setup health check endpoint */ setupEndpoint(app) { if (!this.config.enabled) { this.logger.debug('Health check endpoint disabled'); return; } app.get(this.config.endpoint, async (req, res) => { try { const healthResult = await this.runChecks(); const statusCode = healthResult.status === 'healthy' ? 200 : 503; this.logger.debug('Health check requested', { status: healthResult.status, checkCount: Object.keys(healthResult.checks).length, }); res.status(statusCode).json({ success: healthResult.status === 'healthy', ...healthResult, }); } catch (error) { this.logger.error(error, { context: 'HealthCheckManager.endpoint', }); res.status(500).json({ success: false, status: 'unhealthy', error: 'Health check failed', timestamp: new Date().toISOString(), }); } }); this.logger.info(`Health check endpoint available at ${this.config.endpoint}`); } } exports.HealthCheckManager = HealthCheckManager;