From a1c26a4c4d3da974874b39daa92d8c890956b9b8 Mon Sep 17 00:00:00 2001 From: MikeyBurkman Date: Mon, 2 Oct 2017 11:18:39 -0400 Subject: [PATCH] Lots of clean up and better error handling --- .editorconfig | 13 ++++ package.json | 14 ++-- server.js | 166 ++++++++++++++++++++++------------------------ tests/app_test.js | 57 ++++++++-------- 4 files changed, 130 insertions(+), 120 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..54d958d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +# Tells the .editorconfg plugin to stop searching once it finds this file +root = true + +[*] +indent_size = 2 +indent_style = space +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/package.json b/package.json index d802fd6..2807a14 100644 --- a/package.json +++ b/package.json @@ -4,18 +4,18 @@ "description": "Node.js sample app for OpenShift 3", "main": "server.js", "dependencies": { - "chai": "^3.5.0", - "chai-http": "^2.0.1", "ejs": "^2.4.1", "express": "^4.13.4", - "mocha": "^2.4.5", "mongodb": "^2.1.16", - "morgan": "^1.7.0", - "object-assign":"4.1.0" + "morgan": "^1.7.0" + }, + "devDependencies": { + "chai": "^3.5.0", + "chai-http": "^2.0.1", + "mocha": "^2.4.5" }, "engine": { - "node": "*", - "npm": "*" + "node": ">=4" }, "scripts": { "start": "node server.js", diff --git a/server.js b/server.js index 0415948..b43d9a6 100644 --- a/server.js +++ b/server.js @@ -1,105 +1,97 @@ +'use strict'; + // OpenShift sample Node application -var express = require('express'), - app = express(), - morgan = require('morgan'); - -Object.assign=require('object-assign') +const express = require('express'), + app = express(), + morgan = require('morgan'), + MongoClient = require('mongodb').MongoClient; app.engine('html', require('ejs').renderFile); -app.use(morgan('combined')) +app.use(morgan('combined')); -var port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080, - ip = process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0', - mongoURL = process.env.OPENSHIFT_MONGODB_DB_URL || process.env.MONGO_URL, - mongoURLLabel = ""; +const port = process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080, + ip = process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0', + mongoInfo = getMongoInfo(); -if (mongoURL == null && process.env.DATABASE_SERVICE_NAME) { - var mongoServiceName = process.env.DATABASE_SERVICE_NAME.toUpperCase(), - mongoHost = process.env[mongoServiceName + '_SERVICE_HOST'], - mongoPort = process.env[mongoServiceName + '_SERVICE_PORT'], - mongoDatabase = process.env[mongoServiceName + '_DATABASE'], - mongoPassword = process.env[mongoServiceName + '_PASSWORD'] - mongoUser = process.env[mongoServiceName + '_USER']; +const dbPromise = MongoClient.connect(mongoInfo.url); - if (mongoHost && mongoPort && mongoDatabase) { - mongoURLLabel = mongoURL = 'mongodb://'; - if (mongoUser && mongoPassword) { - mongoURL += mongoUser + ':' + mongoPassword + '@'; - } - // Provide UI label that excludes user id and pw - mongoURLLabel += mongoHost + ':' + mongoPort + '/' + mongoDatabase; - mongoURL += mongoHost + ':' + mongoPort + '/' + mongoDatabase; +app.get('/', function (req, res, next) { + return dbPromise.then((db) => { + const countsCol = db.collection('counts'); - } -} -var db = null, - dbDetails = new Object(); - -var initDb = function(callback) { - if (mongoURL == null) return; - - var mongodb = require('mongodb'); - if (mongodb == null) return; - - mongodb.connect(mongoURL, function(err, conn) { - if (err) { - callback(err); - return; - } - - db = conn; - dbDetails.databaseName = db.databaseName; - dbDetails.url = mongoURLLabel; - dbDetails.type = 'MongoDB'; - - console.log('Connected to MongoDB at: %s', mongoURL); - }); -}; - -app.get('/', function (req, res) { - // try to initialize the db on every request if it's not already - // initialized. - if (!db) { - initDb(function(err){}); - } - if (db) { - var col = db.collection('counts'); - // Create a document with request IP and current time of request - col.insert({ip: req.ip, date: Date.now()}); - col.count(function(err, count){ - res.render('index.html', { pageCountMessage : count, dbInfo: dbDetails }); - }); - } else { - res.render('index.html', { pageCountMessage : null}); - } + return countsCol.insert({ ip: req.ip, date: Date.now() }) + .then(() => countsCol.count()) + .then((count) => { + res.render('index.html', { + pageCountMessage: count, + dbInfo: { + databaseName: db.databaseName, + url: mongoInfo.label, + type: 'MongoDB' + } + }); + }) + }) + .catch(next); }); -app.get('/pagecount', function (req, res) { - // try to initialize the db on every request if it's not already - // initialized. - if (!db) { - initDb(function(err){}); - } - if (db) { - db.collection('counts').count(function(err, count ){ - res.send('{ pageCount: ' + count + '}'); - }); - } else { - res.send('{ pageCount: -1 }'); - } +app.get('/pagecount', function (req, res, next) { + return dbPromise.then((db) => db.collection('counts').count()) + .then((count) => res.json({ + pageCount: count + })) + .catch(next); }); // error handling -app.use(function(err, req, res, next){ - console.error(err.stack); +app.use(function (err, req, res, next) { + console.error(err.stack || err); res.status(500).send('Something bad happened!'); }); -initDb(function(err){ - console.log('Error connecting to Mongo. Message:\n'+err); +app.listen(port, ip, () => console.log('Server running on http://%s:%s', ip, port)); + +// In case there was an error initializing the database +dbPromise.catch((err) => { + console.error('Error initializing database:', err.stack || err); + process.exit(-1); }); -app.listen(port, ip); -console.log('Server running on http://%s:%s', ip, port); -module.exports = app ; + +function getMongoInfo() { + const mongoURL = process.env.OPENSHIFT_MONGODB_DB_URL || process.env.MONGO_URL; + if (mongoURL) { + return { + url: mongoURL, + label: '' + }; + } + + const serviceName = process.env.DATABASE_SERVICE_NAME; + if (!serviceName) { + throw new Error('One of OPENSHIFT_MONGODB_DB_URL|MONGO_URL|DATABASE_SERVICE_NAME env variables must be defined'); + } + + const mongoHost = process.env[mongoServiceName + '_SERVICE_HOST'], + mongoPort = process.env[mongoServiceName + '_SERVICE_PORT'], + mongoDatabase = process.env[mongoServiceName + '_DATABASE'], + mongoPassword = process.env[mongoServiceName + '_PASSWORD'] + mongoUser = process.env[mongoServiceName + '_USER']; + + if (!mongoHost || !mongoPort || !mongoDatabase) { + throw new Error('When using DATABASE_SERVICE_NAME, you must also provide _SERVICE_HOST, _SERVICE_PORT, and _DATABASE env variables'); + } + + let mongoAuth = ''; + if (mongoUser && mongoPassword) { + mongoAuth = mongoUser + ':' + mongoPassword + '@'; + } + + const url = mongoHost + ':' + mongoPort + '/' + mongoDatabase; + return { + url: 'mongodb://' + mongoAuth + url, + label: 'mongodb://' + url + }; + +} diff --git a/tests/app_test.js b/tests/app_test.js index 28da5a0..5815520 100644 --- a/tests/app_test.js +++ b/tests/app_test.js @@ -1,31 +1,36 @@ -var server = require('../server'), - chai = require('chai'), - chaiHTTP = require('chai-http'), - should = chai.should(); +'use strict'; + +const server = require('../server'), + chai = require('chai'), + chaiHTTP = require('chai-http'), + should = chai.should(); chai.use(chaiHTTP); -reqServer = process.env.HTTP_TEST_SERVER || server +const reqServer = process.env.HTTP_TEST_SERVER || server; -describe('Basic routes tests', function() { +describe('Basic routes tests', function () { + it('GET to / should return 200', function (done) { + chai.request(reqServer) + .get('/') + .end(function (err, res) { + if (err) { + return done(err); + } + res.should.have.status(200); + done(); + }); + }); - it('GET to / should return 200', function(done){ - chai.request(reqServer) - .get('/') - .end(function(err, res) { - res.should.have.status(200); - done(); - }) - - }) - - it('GET to /pagecount should return 200', function(done){ - chai.request(reqServer) - .get('/pagecount') - .end(function(err, res) { - res.should.have.status(200); - done(); - }) - - }) -}) + it('GET to /pagecount should return 200', function (done) { + chai.request(reqServer) + .get('/pagecount') + .end(function (err, res) { + if (err) { + return done(err); + } + res.should.have.status(200); + done(); + }); + }); +});