Skip to content

Instantly share code, notes, and snippets.

@jacekd
Last active August 29, 2015 14:16
Show Gist options
  • Save jacekd/19dc573a66c9f994ce00 to your computer and use it in GitHub Desktop.
Save jacekd/19dc573a66c9f994ce00 to your computer and use it in GitHub Desktop.
mongodb explorer
/**
* Main Server file
* @description: this file should iterate over the collections with filters if ones are passed and retrieve the data
* @author: Jacek Dominiak
* @copyright: Jacek Dominiak
* @created: 11/03/15
*/
// ---------------------------------
// import config
var config = require('./config');
// ---------------------------------
// definition the application
var express = require('express')
, app = express();
// make logger
var morgan = require('morgan')
, fs = require('fs');
app.use(morgan('combined', {
stream : fs.createWriteStream(config.app.LOGFILE, {
flags: 'a'
})
}));
// server function
var server = {
start: function () {
var instance = app.listen(config.app.PORT || 9999, function () {
// catch the configuration
var host = instance.address().address
, port = instance.address().port;
console.log('Server instance started on http://%s:%s', host, port);
});
}
};
// ---------------------------------
// connect to the database
var mongojs = require('mongojs');
/**
* Prepare the URL for the connection
* @param config
* @returns {string}
*/
function prepareDbUrl (config) {
var connectionString = '';
if (!!config.db && !!config.db.USERNAME && config.db.USERNAME.length > 0) {
connectionString += config.db.USERNAME + ':' + config.db.PASSWORD + '@';
}
return connectionString + config.db.HOST + ':' + config.db.PORT + '/' + config.db.DATABASE;
}
// connect to the database
var db = mongojs(prepareDbUrl(config));
// ---------------------------------
// handle the data fetch and return the data
app.get('/api/:collection', function (req, res) {
var collection = db.collection(req.params.collection);
collection.find(req.query || {}, function (err, data) {
if (err) return res.status(500).send(err);
return res.status(200).json(data);
});
});
// ---------------------------------
// start the application instance
server.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment