Files
cc-platform-core/server/health.js
2026-03-26 15:00:49 -04:00

56 lines
1.6 KiB
JavaScript

/**
* @cc-platform/server/health — Standardized health check endpoint
*
* Provides a consistent /api/health (or custom path) endpoint across
* all platform services. Reports service name, uptime, and extensible
* status information.
*
* Usage:
* const { createHealthEndpoint } = require('@cc-platform/server/health');
* createHealthEndpoint(app, {
* serviceName: 'inventory-manager',
* getExtras: () => ({
* bridgeConnected: bridgeClients.size > 0,
* webClients: webClients.size,
* }),
* });
*/
'use strict';
/**
* Register a health check endpoint on an Express app.
*
* @param {Express.Application} app - Express app instance
* @param {Object} [opts={}] - Options
* @param {string} [opts.path='/api/health'] - Endpoint path
* @param {string} [opts.serviceName='unknown'] - Service identifier
* @param {Function} [opts.getExtras] - Returns additional status fields: () => Object
*/
function createHealthEndpoint(app, opts = {}) {
const startTime = Date.now();
const healthPath = opts.path || '/api/health';
const serviceName = opts.serviceName || 'unknown';
app.get(healthPath, (_req, res) => {
const status = {
status: 'ok',
service: serviceName,
uptime: Math.floor((Date.now() - startTime) / 1000),
timestamp: new Date().toISOString(),
};
if (opts.getExtras) {
try {
Object.assign(status, opts.getExtras());
} catch (e) {
status.warning = `Health extras error: ${e.message}`;
}
}
res.json(status);
});
}
module.exports = { createHealthEndpoint };