From b79949d360cdcb27611874e9a68130d8349b78b6 Mon Sep 17 00:00:00 2001 From: Tri Nguyen Date: Sun, 8 Jul 2018 16:39:12 -0400 Subject: [PATCH] feat(health-check): extend info response with the resolved health-check promise --- README.md | 9 ++++++++- lib/terminus.js | 12 +++++++++--- lib/terminus.spec.js | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 98c5bac..89da7a9 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,13 @@ function onShutdown () { console.log('cleanup finished, server is shutting down'); } +function healthCheck () { + return Promise.resolve( + // optionally include a resolve value to be included as + // info in the healthcheck response + ) +} + const server = http.createServer((request, response) => { response.end( ` @@ -47,7 +54,7 @@ const server = http.createServer((request, response) => { const options = { // healtcheck options healthChecks: { - '/healthcheck': check // a promise returning function indicating service health + '/healthcheck': healthCheck // a promise returning function indicating service health }, // cleanup options diff --git a/lib/terminus.js b/lib/terminus.js index e26ce3a..6cb4c06 100644 --- a/lib/terminus.js +++ b/lib/terminus.js @@ -15,8 +15,14 @@ function noopResolves () { return Promise.resolve() } -function sendSuccess (res) { +function sendSuccess (res, info) { res.statusCode = 200 + if (info) { + return res.end(JSON.stringify({ + status: 'ok', + info: info + })) + } res.end(SUCCESS_RESPONSE) } @@ -42,8 +48,8 @@ function decorateWithHealthCheck (server, options) { return sendFailure(res) } healthChecks[req.url]() - .then(() => { - sendSuccess(res) + .then((info) => { + sendSuccess(res, info) }) .catch((error) => { logger('healthcheck failed', error) diff --git a/lib/terminus.spec.js b/lib/terminus.spec.js index 8df22ff..5d4a483 100644 --- a/lib/terminus.spec.js +++ b/lib/terminus.spec.js @@ -54,6 +54,39 @@ describe('Terminus', () => { .catch(done) }) + it('includes info on resolve', (done) => { + let onHealthCheckRan = false + + terminus(server, { + healthChecks: { + '/health': () => { + onHealthCheckRan = true + return Promise.resolve({ + version: '1.0.0' + }) + } + } + }) + server.listen(8000) + + fetch('http://localhost:8000/health') + .then(res => { + expect(res.status).to.eql(200) + expect(onHealthCheckRan).to.eql(true) + return res.json() + }) + .then(json => { + expect(json).to.deep.eql({ + status: 'ok', + info: { + version: '1.0.0' + } + }) + done() + }) + .catch(done) + }) + it('returns 503 on reject', (done) => { let onHealthCheckRan = false let loggerRan = false