1.0.3 • Published 7 months ago

health-check-services v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

Health Check Function

Overview

The health check functionality allows developers to monitor the status of various services in the system. It checks the availability of each service by running their corresponding health check functions. Each service will either return true, null, undefined, or void to indicate the service is UP, or return false or throw an error to indicate the service is DOWN.

This is useful for monitoring the health of essential components in your application, such as databases, third-party APIs, and internal services.

Installation

Install the package using npm:

npm install health-check-services

Or with Yarn:

yarn add health-check-services

Usage

Step 1: Define the Health Check Functions for Each Service

Each service in your application must expose a function that will check its health. The function should either:

  • Return true, null, undefined, or void to indicate the service is UP.
  • Return false or throw an error to indicate the service is DOWN.

Example Service Health Check Functions:

class DatabaseService {
  async checkDatabaseHealth(): Promise<boolean | void> {
    // Logic to check the database health (e.g., a query to check connectivity)
    return true; // Indicates that the database is UP
  }
  
  async otherservice(): Promise<boolean | void> {
    // Logic to check the other service health
    return false; // Indicates that this service is DOWN
  }
}

Step 2: Call getHealthCheckStatus Function

The getHealthCheckStatus function is the main entry point for performing the health checks. It takes an object where the key is the service name and the value is the corresponding health check function.

Example Usage of getHealthCheckStatus:

const healthCheckResponses = await getHealthCheckStatus({
  database: () => this.databaseService.checkDatabaseHealth(),
  otherservice: () => this.databaseService.otherservice(),
});

return healthCheckResponses;

The getHealthCheckStatus function returns an object containing the health check status of all services.

Step 3: Customize Service Health Checks

You can easily add additional services by adding new key-value pairs to the input object of getHealthCheckStatus. Each key should be a service name, and the value should be a function that performs the health check for that service.

Example with Additional Service:

const healthCheckResponses = await getHealthCheckStatus({
  database: () => this.databaseService.checkDatabaseHealth(),
  otherservice: () => this.databaseService.otherservice(),
  paymentGateway: () => this.paymentGatewayService.checkHealth(),
});

return healthCheckResponses;

Response Structure

The getHealthCheckStatus function returns an object with the following properties:

  • runtimeMs: The total runtime in milliseconds of all health checks.
  • timestamp: The timestamp of when the health check was performed.
  • status: The overall status of the system ('UP' or 'DOWN').
  • services: An object containing the health check responses for each service. Each key is the service name, and the value is a healthCheckStatusRespType object.

Each healthCheckStatusRespType Object Contains:

  • timestamp: The timestamp when the health check was performed.
  • runtimeMs: The runtime of the individual service check in milliseconds.
  • status: The status of the service ('UP' or 'DOWN').
  • error: Any error that occurred during the health check, if applicable.

Example Response:

{
  "runtimeMs": 50,
  "timestamp": "2025-01-03T12:00:00Z",
  "status": "UP",
  "services": {
    "database": {
      "timestamp": "2025-01-03T12:00:00Z",
      "runtimeMs": 10,
      "status": "UP"
    },
    "otherservice": {
      "timestamp": "2025-01-03T12:00:01Z",
      "runtimeMs": 20,
      "status": "DOWN",
      "error": "Service unavailable"
    },
    "paymentGateway": {
      "timestamp": "2025-01-03T12:00:02Z",
      "runtimeMs": 15,
      "status": "UP"
    }
  }
}

Error Handling

If any service health check function throws an error or returns false, the status for that service will be marked as DOWN. The error will be captured and displayed in the response under the error field.

Optional Query Parameter

You can pass an optional query parameter to the getHealthCheckStatus function, which is a record of service names and their respective statuses. If the status of a service is set to 1 in the query, the status will be shown as part of the response even if it's DOWN. If not specified, only the UP services are shown by default.

Example with Query Parameter:

const healthCheckResponses = await getHealthCheckStatus({
  database: () => this.databaseService.checkDatabaseHealth(),
  otherservice: () => this.databaseService.otherservice(),
}, { otherservice: 1 });

return healthCheckResponses;

Adding the Health Check Functionality to a Server

To make the health check functionality available as an API endpoint, you can create a GET route on your server. For example, you can add a /health-check endpoint to expose the health status.

Step 1: Create the Health Check Endpoint

Add the following route to your server:

Example with Express.js:

import express from 'express';
import getHealthCheckStatus from 'health-check-services';

const app = express();

app.get('/health-check', async (req, res) => {
  try {
    const healthCheckResponses = await getHealthCheckStatus({
      database: () => this.databaseService.checkDatabaseHealth(),
      otherservice: () => this.databaseService.otherservice(),
    });

    res.status(200).json(healthCheckResponses);
  } catch (error) {
    res.status(500).json({ error: 'Health check failed', details: error });
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Step 2: Test the Endpoint

Start your server and navigate to http://HOST.com/health-check in your browser or API testing tool. You should see a JSON response with the health status of all configured services.

Step 3: Add Additional Services

To monitor more services, simply extend the object passed to getHealthCheckStatus with additional key-value pairs representing the service name and its health check function.

Example:

app.get('/health-check', async (req, res) => {
  try {
    const healthCheckResponses = await getHealthCheckStatus({
      database: () => this.databaseService.checkDatabaseHealth(),
      otherservice: () => this.databaseService.otherservice(),
      paymentGateway: () => this.paymentGatewayService.checkHealth(),
    });

    res.status(200).json(healthCheckResponses);
  } catch (error) {
    res.status(500).json({ error: 'Health check failed', details: error });
  }
});

Conclusion

This health check function is a powerful tool for monitoring the availability of critical services in your system. By adding the relevant service health check functions, you can quickly determine which services are operational and which need attention. The flexible input and output structures make it easy to integrate into various systems and expand to new services.

1.0.3

7 months ago

1.0.2

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago