aboutsummaryrefslogtreecommitdiff
path: root/node_modules/mongo-factory/index.js
blob: 085c25c61b7116ce009b6a180fa385954c670634 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 * Creates and manages the Mongo connection pool
 *
 * @type {exports}
 */
var Promise = require('es6-promise').Promise;
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var _ = require('underscore');

// Store all instantiated connections.
var connections = [];

module.exports = function() {

  return {

    /**
     * Gets a Mongo connection from the pool.
     *
     * If the connection pool has not been instantiated yet, it is first
     * instantiated and a connection is returned.
     *
     * @returns {Promise|Db} - A promise object that resolves to a Mongo db object.
     */
    getConnection: function getConnection(connectionString) {
      return new Promise(function(resolve, reject) {
        // If connectionString is null or undefined, return an error.
        if (_.isEmpty(connectionString)) {
          return reject('getConnection must be called with a mongo connection string');
        }

        // Check if a connection already exists for the provided connectionString.
        var pool = _.findWhere(connections, { connectionString: connectionString });

        // If a connection pool was found, resolve the promise with it.
        if (pool) {
          return resolve(pool.db);
        }

        // If the connection pool has not been instantiated,
        // instantiate it and return the connection.
        MongoClient.connect(connectionString, function(err, database) {
          if (err) {
            return reject(err);
          }

          // Store the connection in the connections array.
          connections.push({
            connectionString: connectionString,
            db: database
          });

          return resolve(database);
        });
      });
    },

    /**
     * Exposes Mongo ObjectID function.
     *
     * @returns {Function} - Mongo ObjectID function
     */
    ObjectID: function() {
      return mongo.ObjectID();
    }
  };
}();