refactor server.js

This commit is contained in:
Victor 2016-08-18 22:52:12 +02:00
parent 0e748ed338
commit d23abe66c5
2 changed files with 121 additions and 89 deletions

View file

@ -9,9 +9,8 @@
"ejs": "^2.4.1", "ejs": "^2.4.1",
"express": "^4.13.4", "express": "^4.13.4",
"mocha": "^2.4.5", "mocha": "^2.4.5",
"mongodb": "^2.1.16", "mongoose": "^4.5.9",
"morgan": "^1.7.0", "morgan": "^1.7.0"
"object-assign":"4.1.0"
}, },
"engine": { "engine": {
"node": "*", "node": "*",
@ -19,7 +18,7 @@
}, },
"scripts": { "scripts": {
"start": "node server.js", "start": "node server.js",
"test": "IP=0.0.0.0 PORT=3030 mocha --timeout 5000 tests/*_test.js" "test": "HOST=0.0.0.0 PORT=3030 mocha --timeout 5000 tests/*_test.js"
}, },
"repository": { "repository": {
"type": "git", "type": "git",

203
server.js
View file

@ -1,107 +1,140 @@
// OpenShift sample Node application 'use strict'
var express = require('express'),
fs = require('fs'),
app = express(),
eps = require('ejs'),
morgan = require('morgan');
Object.assign=require('object-assign')
app.engine('html', require('ejs').renderFile); /*
NodeJS OpenShift Origin example for node 0.1xx and 4.xx
*/
var express = require('express')
var morgan = require('morgan')
var mongoose = require('mongoose')
var app = module.exports = express()
app.set('view engine', 'html')
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, var mongoURL = process.env.OPENSHIFT_MONGODB_DB_URL || process.env.MONGO_URL
ip = process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0', var mongoURLLabel = ''
mongoURL = process.env.OPENSHIFT_MONGODB_DB_URL || process.env.MONGO_URL,
mongoURLLabel = "";
if (mongoURL == null && process.env.DATABASE_SERVICE_NAME) { if (mongoURL == null && process.env.DATABASE_SERVICE_NAME) {
var mongoServiceName = process.env.DATABASE_SERVICE_NAME.toUpperCase(), // TODO: improve a bit on this ugliness
mongoHost = process.env[mongoServiceName + '_SERVICE_HOST'], let mongoServiceName = process.env.DATABASE_SERVICE_NAME.toUpperCase()
mongoPort = process.env[mongoServiceName + '_SERVICE_PORT'], let mongoHost = process.env[mongoServiceName + '_SERVICE_HOST']
mongoDatabase = process.env[mongoServiceName + '_DATABASE'], let mongoPort = process.env[mongoServiceName + '_SERVICE_PORT']
mongoPassword = process.env[mongoServiceName + '_PASSWORD'] let mongoDatabase = process.env[mongoServiceName + '_DATABASE']
mongoUser = process.env[mongoServiceName + '_USER']; let mongoPassword = process.env[mongoServiceName + '_PASSWORD']
let mongoUser = process.env[mongoServiceName + '_USER']
if (mongoHost && mongoPort && mongoDatabase) { if (mongoHost && mongoPort && mongoDatabase) {
mongoURLLabel = mongoURL = 'mongodb://'; let mongoURLLabel = mongoURL = 'mongodb://'
if (mongoUser && mongoPassword) { if (mongoUser && mongoPassword) {
mongoURL += mongoUser + ':' + mongoPassword + '@'; mongoURL += mongoUser + ':' + mongoPassword + '@'
} }
// Provide UI label that excludes user id and pw // Provide UI label that excludes user id and pw
mongoURLLabel += mongoHost + ':' + mongoPort + '/' + mongoDatabase; mongoURLLabel += mongoHost + ':' + mongoPort + '/' + mongoDatabase
mongoURL += mongoHost + ':' + mongoPort + '/' + mongoDatabase; mongoURL += mongoHost + ':' + mongoPort + '/' + mongoDatabase
} }
} }
var db = null,
dbDetails = new Object();
var initDb = function(callback) { var dbConnection = function () {
if (mongoURL == null) return; let db = mongoose.connect(mongoURL)
// clear previously assigned event listeners so that we don't reach the limit
var mongodb = require('mongodb'); db.connection.removeAllListeners()
if (mongodb == null) return; db.connection.once('error', function (err) {
console.error('Database connection error: %s', err)
mongodb.connect(mongoURL, function(err, conn) { })
if (err) { db.connection.once('disconnected', function () {
callback(err); console.log('Database disconnected from %s', mongoURL)
return; })
db.connection.once('open', function () {
db.dbDetails = {
type: 'MongoDB',
databaseName: db.name,
url: mongoURLLabel
} }
console.log('Connected to database %s', mongoURL)
})
db = conn; db.model = function () {
dbDetails.databaseName = db.databaseName; // only register the schema if it wasn't previously registered.
dbDetails.url = mongoURLLabel; // otherwise return the model.
dbDetails.type = 'MongoDB'; if (!mongoose.models.Counts) {
return mongoose.model('Counts',
new db.Schema({
ip: String,
date: {type: Date, default: Date.now}
})
)
} else {
return mongoose.model('Counts')
}
}
return db
}
console.log('Connected to MongoDB at: %s', mongoURL); var countHits = function (db, callback) {
}); let countsModel = db.model()
}; countsModel.count({}, function (err, count) {
if (err) {
console.error('An error occured retrieving data %s', err)
callback(undefined)
}
callback(count)
})
}
function insertHits (ip, callback) {
let db = dbConnection()
let NewCountsModel = new db.model()
new NewCountsModel({ip: ip})
.save(function (err) {
if (err) {
console.error('An error occured while saving the data %s', err)
}
countHits(db, function (count) {
let results = {
dbInfo: db.dbDetails,
pageCountMessage: count
}
callback(results)
})
})
}
app.get('/', function (req, res) { app.get('/', function (req, res) {
// try to initialize the db on every request if it's not already insertHits(req.ip, function (results) {
// initialized. results || {
if (!db) { dbInfo: null,
initDb(function(err){}); pageCountMessage: null
} }
if (db) { mongoose.disconnect()
var col = db.collection('counts'); res.render('index', {
// Create a document with request IP and current time of request dbInfo: results.dbInfo,
col.insert({ip: req.ip, date: Date.now()}); pageCountMessage: results.pageCountMessage
col.count(function(err, count){ })
res.render('index.html', { pageCountMessage : count, dbInfo: dbDetails }); })
}); })
} else {
res.render('index.html', { pageCountMessage : null});
}
});
app.get('/pagecount', function (req, res) { app.get('/pagecount', function (req, res) {
// try to initialize the db on every request if it's not already let db = dbConnection()
// initialized. countHits(db, function (results) {
if (!db) { results || {'pageCount': -1}
initDb(function(err){}); db.disconnect()
res.send(JSON.stringify({pageCount: results}))
})
})
var server = app.listen(process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080, process.env.HOST || '0.0.0.0')
server.once('error', function (err) {
if (err) {
console.error('Server error: %s', err)
} }
if (db) { })
db.collection('counts').count(function(err, count ){
res.send('{ pageCount: ' + count + '}');
});
} else {
res.send('{ pageCount: -1 }');
}
});
// error handling server.once('listening', function () {
app.use(function(err, req, res, next){ let host = server.address().address
console.error(err.stack); let port = server.address().port
res.status(500).send('Something bad happened!'); console.log('Application accessible on http://%s:%s', host, port)
}); })
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);
module.exports = app ;