diff --git a/lib/middleware/status.js b/lib/middleware/status.js new file mode 100644 index 0000000..860d909 --- /dev/null +++ b/lib/middleware/status.js @@ -0,0 +1,23 @@ +'use strict'; + +/** + * Return basic application status information: + * Date the application was started and uptime in JSON format. + * For example: + * ```js + * { + * "started": "2014-06-05T00:26:49.750Z", + * "uptime": 9.394 + * } + * ``` + */ +module.exports = function status() { + const started = new Date(); + + return (req, res) => { + res.send({ + started: started, + uptime: (Date.now() - Number(started)) / 1000, + }); + }; +} diff --git a/lib/services.js b/lib/services.js index eb85c54..a721f59 100644 --- a/lib/services.js +++ b/lib/services.js @@ -16,7 +16,8 @@ const _ = require('lodash'), serverUtils = require('./server-utils'), {SocketIOLoader, Loader} = require('./api'), dotEnv = require('dotenv'), - path = require('path'); + path = require('path'), + status = require('./middleware/status'); // Load environment variables using a local .env file (see: https://www.npmjs.com/package/dotenv) dotEnv.config({path: path.join(process.cwd(), '.env')}); @@ -157,6 +158,9 @@ class Services { this.initialize(); } + // Attach basic health check middleware + this._app.get(mountPoint, status()) + // Run all the package API 'config' functions this._apiLoader.setConfig({ apiLoader: this._apiLoader, diff --git a/test/lib/unit/lib/services_spec.js b/test/lib/unit/lib/services_spec.js index cae8b85..60cc7ac 100644 --- a/test/lib/unit/lib/services_spec.js +++ b/test/lib/unit/lib/services_spec.js @@ -8,8 +8,8 @@ const supertest = require('supertest'), describe('Services', () => { - const packagesPath = './test/fixtures/main-package', - apiPackage1Prefix = '/socket-api-package-1-namespace'; + const packagesPath = './test/fixtures/main-package' + const apiPackage1Prefix = '/socket-api-package-1-namespace' let services, port, @@ -123,4 +123,21 @@ describe('Services', () => { }).toThrowError(/Session store "INVALID STORE" is not supported/i); }); + it('sets a health check endpoint on the restApiRoot', (done) => { + const services = new Services(options); + server = services.start(); + + const request = supertest(server); + + request + .get('/') + .expect(200) + .then((res) => { + expect(res.text).toContain('started'); + expect(res.text).toContain('uptime'); + done(); + }) + .catch(done.fail); + }) + });