-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
365 lines (310 loc) · 10.1 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/**
* index.js
*/
var util = require('util');
var _ = require('underscore');
var async = require('async');
var clor = require("clor");
var MongoClient = require('mongodb').MongoClient;
/**
* Mongo Aggregation Debugger module
*
* Provides ways to debug mongo's aggregation framework
*
* Initialize by providing MongoDb connection credentials
* - host {string} (default: 'localhost') the host info
* - port {number} (default: 27017) the port info
* - username {string} (optional) the mongodb username
* - password {string} (optional) the mongodb password
* - options {object} (opional) standard mongodb options
*/
var mongoAggregationDebugger = function (mongoParams) {
my = {};
my.defaultMongoParams = {
host: 'localhost',
port: 27017,
username: null,
password: null,
options: {}
};
my.mongoParams = _.extend(my.defaultMongoParams, mongoParams || {});
my.collectionName = 'documents';
/**
* Private
*/
var generateDatabaseName;
var debug;
var buildConnectionUrl;
var getMongoConnection;
/**
* Public
*/
var log;
var stages;
var exec;
/**
* that
*/
var that = {};
/*************************************************************************************************
* PRIVATE METHODS
************************************************************************************************/
/**
* Generates a rather unique database name
* @return {string} the database name
*/
generateDatabaseName = function () {
return 'mongo_aggregation_debugger_' + process.pid + '_' + Date.now();
};
/**
* Builds the mongodb connection url from the params passed
* @return {string} the mongodb connection url
*/
buildConnectionUrl = function () {
if (!my.mongoParams.host) {
my.mongoParams.host = my.defaultMongoParams.host;
}
var url = 'mongodb://';
if (my.mongoParams.username && my.mongoParams.password) {
url += my.mongoParams.username + ':' + my.mongoParams.password + '@';
}
url += my.mongoParams.host;
if (my.mongoParams.port) {
url += ':' + my.mongoParams.port;
}
my.debugDatabaseName = my.debugDatabaseName || generateDatabaseName();
url += '/' + my.debugDatabaseName;
return url;
};
/**
* Get the mongodb's Db instance
* @param {function} cb(err, db)
*/
getMongoConnection = function (cb) {
MongoClient.connect(buildConnectionUrl(), my.mongoParams.options, cb);
};
/**
* Partition an aggregation query into several subsets
* @param {array} query The aggregation query
* @param {boolean} skipStages Whether to directly run the full query or not
* @return {array} Query parts
*/
partitionQuery = function (query, skipStages) {
var queryParts = [];
if (skipStages) {
queryParts.push(query);
} else {
query.forEach(function (queryPart, index) {
if (index === 0) {
queryParts.push([ queryPart ]);
} else {
var part = _.clone(queryParts[index - 1]);
part.push(queryPart);
queryParts.push(part);
}
});
}
return queryParts;
};
/**
* Actually runs the debugging part
* @param {mixed} data An array of objects that will be the data
* the aggregation will be performed on.
* Also accepts a single object.
* @param {array} query The aggregation query
* @param {function} beforeEach Callback called before each stage of the aggregation.
* Arguments passed:
* - queryPart {array} The query run for this stage
* of the aggregation
* - index {number} The current aggregation stage number
* @param {function} afterEach Callback called after each stage of the aggregation.
* Arguments passed:
* - results {array} The results of that aggregation stage
* - index {number} The current aggregation stage number
* @param {boolean} skipStages (optional, default: false) Whether to directly run the
* full query or not
* @param {function} cb(err)
*/
debug = function (data, query, beforeEach, afterEach, skipStages, cb) {
var doSkipStegaes = false;
if (typeof skipStages === 'function' && typeof cb === 'undefined') {
cb = skipStages;
doSkipStages = false;
} else if (typeof skipStages === 'boolean') {
doSkipStages = skipStages;
} else {
return cb(new Error('Invalid `skipStages` value'));
}
if (typeof cb !== 'function') {
throw new Error('Invalid callback');
}
if (!Array.isArray(data)) {
if (data && typeof data === 'object') {
data = [ data ];
} else {
return cb(new Error('Invalid `data`'));
}
}
if (!Array.isArray(query)) {
return cb(new Error('Invalid `query`'));
}
if (typeof beforeEach !== 'function') {
beforeEach = function () {};
}
if (typeof afterEach !== 'function') {
afterEach = function () {};
}
getMongoConnection(function (err, db) {
if (err) {
return cb(err);
}
var collection = db.collection(my.collectionName);
var queryParts = partitionQuery(query, doSkipStages);
var series = [
function insert (cb) {
collection.insert(data, cb);
}
];
queryParts.forEach(function (queryPart, index) {
series.push(
function (cb) {
beforeEach(queryPart, index);
(function (index) {
collection.aggregate(queryPart, function (err, results) {
if (err) {
return cb(err);
}
afterEach(results, index);
return cb();
});
})(index);
}
);
});
series.push(
function dropDatabase (cb) {
db.dropDatabase(cb);
}
);
async.series(series, function (err) {
if (err) {
return db.dropDatabase(function (anotherErr) {
db.close();
cb(anotherErr || err);
});
}
db.close();
return cb();
});
});
};
/*************************************************************************************************
* PUBLIC METHODS
************************************************************************************************/
/**
* Logging mode, displays results in console
* @param {mixed} data An array of objects that will be the data
* the aggregation will be performed on.
* Also accepts a single object.
* @param {array} query The aggregation query
* @param {object} options (optional) Display options:
* - showQuery {boolean} (default: false) Outputs each stage's query
* @param {function} cb(err)
*/
log = function (data, query, options, cb) {
if (typeof options === 'function' && typeof cb === 'undefined') {
cb = options;
}
if (typeof cb !== 'function') {
cb = function () {};
}
options = options || {};
util.debug(clor.cyan('Mongo aggregation debugger [Start]\n'));
var beforeEach = function (queryPart, index) {
var operationType = _.keys(queryPart[queryPart.length - 1])[0];
console.log(clor.bgWhite.black(' Stage ' + (index + 1) + ' ') + ' ' +
clor.bgBlue(' ' + operationType + ' '));
if (options.showQuery) {
console.log(util.inspect(queryPart, {
depth: null,
colors: true
}));
console.log('\n' + clor.bgGreen.black(' Results '));
}
};
var afterEach = function (results) {
console.log(util.inspect(results, {
depth: null,
colors: true
}));
console.log('\n');
};
debug(data, query, beforeEach, afterEach, function (err) {
if (err) {
return cb(err);
} else {
util.debug(clor.cyan('Mongo aggregation debugger [End]'));
return cb();
}
});
};
/**
* Programmatic mode, returns an array of each aggregation stage's data
* @param {mixed} data An array of objects that will be the data
* the aggregation will be performed on.
* Also accepts a single object.
* @param {array} query The aggregation query
* @param {function} cb(err, output)
*/
stages = function (data, query, cb) {
if (typeof cb !== 'function') {
cb = function () {};
}
var output = [];
var beforeEach = function (queryPart, index) {
output.push({
query: queryPart
});
};
var afterEach = function (results, index) {
output[index] = output[index] || {};
output[index].results = results;
};
debug(data, query, beforeEach, afterEach, function (err) {
if (err) {
return cb(err);
} else {
return cb(null, output);
}
});
};
/**
* Exec mode, returns only the last result, without running intermediate aggregation stages
* @param {mixed} data An array of objects that will be the data
* the aggregation will be performed on.
* Also accepts a single object.
* @param {array} query The aggregation query
* @param {function} cb(err, output)
*/
exec = function (data, query, cb) {
if (typeof cb !== 'function') {
cb = function () {};
}
var output;
var afterEach = function (results) {
output = results;
};
debug(data, query, null, afterEach, true, function (err) {
if (err) {
return cb(err);
} else {
return cb(null, output);
}
});
};
that.log = log;
that.stages = stages;
that.exec = exec;
return that;
};
module.exports = mongoAggregationDebugger;