-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.js
98 lines (78 loc) · 1.45 KB
/
index.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* Module Dependencies
*/
var mongo = require('mongodb');
var Db = require('./lib/db');
/**
* Expose Db
*/
module.exports = Db;
/**
* Objects to wrap
*/
var wrap = [
'Collection',
'Cursor',
'Db',
'MongoClient'
];
/**
* Expose comongo wrapper
*/
wrap.forEach(function (name) {
Db[name] = require('./lib/' + name.toLowerCase());
});
/**
* Expose everything else
*/
for (var key in mongo) {
if (!Db[key])
Db[key] = mongo[key];
}
/**
* Default configuration
*/
var config = {
host: '127.0.0.1',
port: 27017,
name: 'test',
pool: 5,
collections: []
};
/**
* Set default configuration
*/
Db.configure = function (conf) {
for (var key in conf) {
config[key] = conf[key];
}
};
/**
* Get db attached collections
*/
Db.get = function () {
return function (done) {
var server = new mongo.Server(config.host, config.port);
var db = new mongo.Db(config.name, server, {
w: 1,
poolSize: config.pool
});
db.open(function (err, db) {
if (err) return done(err);
// Wrap
db = new Db(db);
// Attach collections
var collections = config.collections.slice(0);
(function next() {
if (!collections.length)
return done(err, db);
var name = collections.shift();
db.collection(name)(function (err, collection) {
if (err) return done(err);
db[name] = collection;
next();
});
})();
});
};
};