-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
75 lines (58 loc) · 1.88 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
var url = require('url')
, client = require('mongodb').MongoClient
;
var beforeEachRegistered = false;
var afterHookRegistered = false;
module.exports = function(uriString, options) {
options = options || {};
if (typeof uriString == 'function') {
throw new Error("Module being called to clean the db. Please call the module with a mongodb url.");
}
if (!uriString) {
console.warn("!WARNING: no mongodb url provided. Defaulting to mongodb://localhost/test");
uriString = 'mongodb://localhost/test';
}
var db = null;
if (!options.noClear && !beforeEachRegistered) {
if ('function' == typeof beforeEach && beforeEach.length > 0) {
// we're in a test suite that hopefully supports async operations
beforeEach(clearDB);
beforeEachRegistered = true;
}
}
if (!options.noClear && !afterHookRegistered) {
if ('function' == typeof after && after.length > 0) {
// we're in a test suite that hopefully supports async operations
after(closeDB);
afterHookRegistered = true;
}
}
return function(done) {
clearDB(done);
};
function clearDB(done) {
if (db) return clearCollections(done);
client.connect(uriString, function(err, newDb){
if (err) return done(err);
db = newDb;
clearCollections(done);
});
}
function clearCollections(done) {
db.collections(function(err, collections){
if (err) return done(err);
var todo = collections.length;
if (!todo) return done();
collections.forEach(function(collection){
if (collection.collectionName.match(/^system\./)) return --todo;
if (options.skip instanceof Array && options.skip.indexOf(collection.collectionName) > -1) return --todo;
collection.remove({},{safe: true}, function(){
if (--todo === 0) done();
});
});
});
}
function closeDB() {
db.close();
}
};