aboutsummaryrefslogtreecommitdiff
path: root/node_modules/mongo-factory/index.js
diff options
context:
space:
mode:
authornanalelfe <nargiza.nosirova@mail.utoronto.ca>2016-07-18 10:54:08 +0000
committernanalelfe <nargiza.nosirova@mail.utoronto.ca>2016-07-18 10:54:08 +0000
commita35da9f9ccc1124d9b6f4461c7216ffbb0285e2f (patch)
treed5b4b8548caae36a20e1258a8341dab4b3d522d2 /node_modules/mongo-factory/index.js
parent16bbc66ebafc6f1a55e47dbda3f3c0f658fe715c (diff)
parentc1ce89359a7b54ec97b54ce577e5534c180c5c4b (diff)
merged
Diffstat (limited to 'node_modules/mongo-factory/index.js')
-rw-r--r--node_modules/mongo-factory/index.js68
1 files changed, 68 insertions, 0 deletions
diff --git a/node_modules/mongo-factory/index.js b/node_modules/mongo-factory/index.js
new file mode 100644
index 0000000..085c25c
--- /dev/null
+++ b/node_modules/mongo-factory/index.js
@@ -0,0 +1,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();
+ }
+ };
+}();