Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better error handling, use better practices. #140

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -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
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
174 changes: 83 additions & 91 deletions server.js
Original file line number Diff line number Diff line change
@@ -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'))

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 = "";

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'];

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;

}
}
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});
}
app.use(morgan('combined'));

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();

const dbPromise = MongoClient.connect(mongoInfo.url);

app.get('/', function (req, res, next) {
return dbPromise.then((db) => {
const countsCol = db.collection('counts');

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
};

}
57 changes: 31 additions & 26 deletions tests/app_test.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
var server = require('../server'),
chai = require('chai'),
chaiHTTP = require('chai-http'),
should = chai.should();
'use strict';

chai.use(chaiHTTP);

reqServer = process.env.HTTP_TEST_SERVER || server
const server = require('../server'),
chai = require('chai'),
chaiHTTP = require('chai-http'),
should = chai.should();

describe('Basic routes tests', function() {

it('GET to / should return 200', function(done){
chai.request(reqServer)
.get('/')
.end(function(err, res) {
res.should.have.status(200);
done();
})
chai.use(chaiHTTP);

})
const reqServer = process.env.HTTP_TEST_SERVER || server;

it('GET to /pagecount should return 200', function(done){
chai.request(reqServer)
.get('/pagecount')
.end(function(err, res) {
res.should.have.status(200);
done();
})
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 /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();
});
});
});