UNPKG

express-insights

Version:

Production-ready Express middleware for backend health monitoring with metrics, HTML/JSON output, authentication, and service checks.

61 lines (54 loc) 2.68 kB
const validator = require('validator'); const DEFAULT_CONFIG = { route: '/health', htmlResponse: false, style: 'light', message: 'Backend Health Check', version: '1.0.0', includeNetwork: false, includeDisk: false, checks: { database: false, }, authentication: null, rateLimit: null, enableMetrics: false, cors: false, cacheTTL: 5000, timeout: 5000, retries: 1, autoRefreshInterval: 30000, log: { level: 'info', destination: 'console', filePath: './health-check.log', }, resourceThresholds: { memoryUsedPercent: 80, cpuLoad1Min: 2.0, }, }; function validateOptions(options) { const mergedOptions = { ...DEFAULT_CONFIG, log: { ...DEFAULT_CONFIG.log }, resourceThresholds: { ...DEFAULT_CONFIG.resourceThresholds }, checks: { ...DEFAULT_CONFIG.checks }, ...options, }; if (options.log) mergedOptions.log = { ...DEFAULT_CONFIG.log, ...options.log }; if (options.resourceThresholds) mergedOptions.resourceThresholds = { ...DEFAULT_CONFIG.resourceThresholds, ...options.resourceThresholds }; if (options.checks) mergedOptions.checks = { ...DEFAULT_CONFIG.checks, ...options.checks }; const { route, style, log, autoRefreshInterval, resourceThresholds, cors, checks } = mergedOptions; if (typeof route !== 'string' || !route.startsWith('/')) throw new Error('Invalid route: must be a string starting with "/"'); if (!['light', 'dark'].includes(style)) throw new Error('Invalid style: must be "light" or "dark"'); if (!['info', 'warn', 'error'].includes(log.level)) throw new Error('Invalid log level: must be "info", "warn", or "error"'); if (!['console', 'file'].includes(log.destination) && !log.customLogger) throw new Error('Invalid log destination: must be "console", "file", or provide customLogger'); if (!Number.isInteger(autoRefreshInterval) || autoRefreshInterval < 0) throw new Error('Invalid autoRefreshInterval: must be a non-negative integer'); if (resourceThresholds.memoryUsedPercent < 0 || resourceThresholds.memoryUsedPercent > 100) throw new Error('Invalid memoryUsedPercent threshold: must be between 0 and 100'); if (resourceThresholds.cpuLoad1Min < 0) throw new Error('Invalid cpuLoad1Min threshold: must be non-negative'); if (cors !== true && cors !== false && (!cors || !cors.allowedOrigins)) throw new Error('Invalid cors configuration: must be boolean or { allowedOrigins: string | string[] }'); if (typeof checks !== 'object') throw new Error('Invalid checks configuration: must be an object'); return mergedOptions; } module.exports = { DEFAULT_CONFIG, validateOptions };