Skip to content

firstandthird/hapi-health

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

35 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

hapi-health

hapi plugin that exposes a '/health' route that can be used for checking basic health metrics for your server.

Installation

npm install hapi-health

Basic Usage

await server.register({
  plugin: require('hapi-health')
});

Then GET /health you will get back something like:

{
  "host": "sorrynotsorry.local",
  "env": "test",
  "uptime": 0,
  "cpu": { "user": 384085, "system": 48978 },
  "memory": {
    "rss": 47497216,
    "heapTotal": 32874496,
    "heapUsed": 18066608,
    "external": 518509
  }
}

Custom Checks

You can also use hapi server methods to run and return custom checks that will then be returned along with the other metrics. These server methods must accept the parameter signature (request, options), where request will be the hapi request object and options is an object that you specify when you register the plugin. The server must return a JSON object, but they can be either sync or async.

Pass checks as an array, each item in the array should have the following fields:

  • name (required)

    Name of the check, hapi-health will add a field with this name containined the output of the server.method.

  • method (required)

    Name of the server method to call (nested server methods can be called like 'foo.bar.bat').

  • options (optional)

    You can specify an options object that will be passed to the server method when it is invoked.

For example:

server.method('foo', async(request, options) => {
  return {
    user: request.auth.credentials.user,
    result: options.arg1 + 1
  };
});

await server.register({
  plugin: require('hapi-health'),
  options: {
    checks: [
      {
        name: 'My Custom Check',
        method 'foo',
        options: {
          arg1: 2
        }},
    ]
  }
});

Now when you call /health you will get something like:

{
  "host": "sorrynotsorry.local",
  "env": "test",
  "uptime": 0,
  "cpu": { "user": 384085, "system": 48978 },
  "memory": {
    "rss": 47497216,
    "heapTotal": 32874496,
    "heapUsed": 18066608,
    "external": 518509
  },
  "My Custom Check": {
    "user": "myself",
    "result": 3
  }
}

Other Options:

  • auth

    By default the /health route is unprotected, but you can specify a standard hapi auth route config, which will be applied to the route config.

  • token

    When specified, hapi-health will also internally require a '?token=' parameter when calling the /health route. If it does not match or is not present then it will return a 401 Unauthorized. This is in addition to any auth config that has been applied to the route.

  • endpoint

    By default hapi-health uses /health as the endpoint, but you can use this option to specify a different route to use as your health endpoint.