Skip to content

Instantly share code, notes, and snippets.

@jacekd
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save jacekd/19dc573a66c9f994ce00 to your computer and use it in GitHub Desktop.

Select an option

Save jacekd/19dc573a66c9f994ce00 to your computer and use it in GitHub Desktop.

Revisions

  1. jacekd renamed this gist Mar 12, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. jacekd created this gist Mar 12, 2015.
    78 changes: 78 additions & 0 deletions mongodb.explorer
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    /**
    * 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();