0.1.1 • Published 9 months ago

healthcheck-test v0.1.1

Weekly downloads
-
License
AccelByte License
Repository
-
Last release
9 months ago

healthcheck js/ts sdk

This library provides backend service dependencies health check and its telemetry, used for service written in Javascript and Typescript.

The library will execute health check ondemand or periodically in background for all dependencies registered in HealthCheck class.

The result from library is in form of general json object that can be return as http response to health endpoint using any web framework.

Installation guide

yarn add healthcheck-js-sdk

Library usage

Initial setup the HealthCheck object

import {
  AlertLevel,
  HealthCheck,
  newRedisDependencyCheck,
  newS3DependencyCheckByListObjects,
  newSQLDependencyCheck
} from 'healthcheck-js-sdk'

// instantiate health check object with service name and interval for periodic background dependency check
const healthCheck = new HealthCheck({
  name: 'my-service',
  checkIntervalSecond: 60,
})

// add dependency check using provided check function, available function: 
// - newSQLDependencyCheck
// - newRedisDependencyCheck
// - newS3DependencyCheckByListObjects
healthCheck.addDependencyCheck(newSQLDependencyCheck({
    prisma: prismaClient,
    name: 'postgresql',
    // available values: Critical (P0), Important (P1), Utility (P2)
    // is used to adjust the internal alerting priority when this dependency become unhealthy
    alertLevel: AlertLevel.Critical,
}))

// add dependency check manually
healthCheck.addDependencyCheck({
    name: 'my-dependency-1',
    alertLevel: AlertLevel.Utility,
    checkFunction: async () => {
        // code to check for dependency
        // resolve successfully for a healthy result, or
        // throw error to indicate dependency unhealthy
        if (!check()) {
            throw 'dependency checking error'
        }
    }
})

// We need to expose the metrics emitted by this library to opentelemetry MeterProvider for service monitoring and alerting purpose
healthCheck.addMetrics(metricsStorage.meterProvider)

// start periodic background check, the inverval is configured by checkIntervalSecond to every 60s above 
healthCheck.startBackgroundCheck()

Example get the check result and return as response

import { ParameterizedContext } from 'koa'

export const healthzHandler = async (ctx: ParameterizedContext): Promise<void> => {
    // get the result object from health check, results is a json object standard with other healthcheck library
    const results = await healthCheck.getResult()
    ctx.body = results
    ctx.status = isHealthy ? 200 : 500
}

Contribute

Setup the project dependencies

yarn install

Test written in /tests directory

To run unit test:

yarn test

Bundle the library

yarn bundle