Created
April 2, 2014 08:12
-
-
Save olostan/9929989 to your computer and use it in GitHub Desktop.
Promisified Proxy-based MongoDB wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var q = require('q'); | |
var MongoClient = require('mongodb').MongoClient; | |
const dbUrl = require('./config').mongoUrl; | |
var dbConnection; | |
function getDb() { | |
if (dbConnection) return q(dbConnection); | |
dbConnection = q.nfcall(MongoClient.connect, dbUrl).then(function (db) { | |
return dbConnection = db; | |
}); | |
return dbConnection; | |
} | |
//q.longStackSupport = true; | |
function CollectionHandler(cname) { | |
return { | |
get: function (target, name) { | |
return function () { | |
//console.log("collection", cname, "func ", name); | |
var args = arguments; | |
return getDb() | |
.then(function (xdb) { | |
var c = xdb.collection(cname); | |
if (!c[name]) throw new Error("No collection's method: "+name); | |
return q.npost(c, name, args).then(function (result) { | |
if (result && result.constructor.name == 'Cursor') { | |
var h = { | |
get: function (target, name) { | |
if (name == 'promiseDispatch' || name == 'then') return undefined; | |
if (Object.prototype.hasOwnProperty.call(result, name)) { | |
//console.log("making promise for ", name) | |
return q.npost.bind(null, result, name); | |
} else { | |
//console.log(result); | |
throw "Undefined Cursor's function: " + name; | |
} | |
} | |
}; | |
return q(Proxy.create(h, result)); | |
} else | |
return result; | |
}); | |
}); | |
} | |
} | |
} | |
} | |
var dbHandler = { | |
get: function (target, name) { | |
if (name=='ObjectID') return require('mongodb').ObjectID; | |
return Proxy.create(CollectionHandler(name)); | |
} | |
}; | |
var db = Proxy.create(dbHandler); | |
module.exports = db; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment