/
pop.js
657 lines (558 loc) · 15 KB
/
pop.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
/*
Defines and implements the Mongopop Restful API by adding 'get' and 'post'
routes to the router.
*/
var getIP = require('external-ip')();
var request = require("request");
var express = require('express');
var router = express.Router();
var config = require('../config.js');
var DB = require('../javascripts/db');
var publicIP; // IP address of the server running the Mongopop service
getIP(function (err, ip) {
// Stores the IP address of the server where the Mongopop service is running
if (err) {
console.log("Failed to retrieve IP address: " + err.message);
throw err;
}
console.log("Mongopop API running on " + ip + ":" + config.expressPort);
publicIP = ip;
});
router.get('/', function(req, res, next) {
// This isn't part of API and is just used from a browser or curl to test that
// "/pop" is being routed correctly.
var testObject = {
"AppName": "MongoPop",
"Version": 1.0
}
res.json(testObject);
});
router.get('/ip', function(req, res, next) {
// Sends a response with the IP address of the server running this service.
res.json({"ip": publicIP});
});
router.get('/config', function(req, res, next) {
res.json(config.client);
})
function requestJSON(requestURL) {
// Retrieve an array of example JSON documents from an external source
// e.g. mockaroo.com. Returns a promise that either resolves to the results
// from the JSON service or rejects with the received error.
return new Promise(function (resolve, reject){
// Mockaroo can have problems with https - this is random sample data so by
// definition shouldn't need to be private
finalDocURL = requestURL.replace('https', 'http');
request({url: finalDocURL, json: true}, function (error, response, body) {
if (error || response.statusCode != 200) {
console.log("Failed to fetch documents: " + error.message);
reject(error.message);
} else {
resolve(body);
}
})
})
}
router.post('/addDocs', function(req, res, next) {
/* Request from client to add a number of documents to a collection; the request
should be of the form:
{
MongoDBURI: string; // Connect string for MongoDB instance
collectionName: string;
dataSource: string; // e.g. a Mockaroo.com URL to produce example docs
numberDocs: number; // How many (in thousands) documents sould be added
unique: boolean; // Whether each batch of 1,000 documents should be distinct
// from the others (much slower if set to true)
}
The response will contain:
{
success: boolean;
count: number; // How many documents were added (in thousands)
error: string;
}
*/
var requestBody = req.body;
var uniqueDocs = req.body.unique;
var batchesCompleted = 0;
var database = new DB;
var docURL = requestBody.dataSource;
database.connect(requestBody.MongoDBURI)
.then(
function() {
if (uniqueDocs) {
// Need to fetch another batch of unique documents for each batch
// of 1,000 docs
for (i = 0; i < requestBody.numberDocs; i++) {
// Fetch the example documents (based on the caller's source URI)
requestJSON(docURL)
.then(
function(docs) {
// The first function provided as a parameter to "then"
// is called if the promise is resolved successfully. The
// "requestJSON" method returns the retrieved documents
// which the code in this function sees as the "docs"
// parameter. Write these docs to the database:
database.popCollection(requestBody.collectionName, docs)
.then(
function(results) {
return batchesCompleted++;
},
function(error) {
// The second function provided as a parameter to "then"
// is called if the promise is rejected. "err" is set to
// to the error passed by popCollection
database.close();
resultObject = {
"success": false,
"count": batchesCompleted,
"error": "Failed to write mock data: " + error
};
res.json(resultObject);
throw(false);
}
)
.then(
function() {
// If all off the batches have been (successfully) added
// then build and send the response.
if (batchesCompleted == requestBody.numberDocs) {
database.close();
console.log('Wrote all Mock data');
resultObject = {
"success": true,
"count": batchesCompleted,
"error": ""
};
res.json(resultObject);
}
},
function(error) {}
)
},
function(error) {
database.close();
resultObject = {
"success": false,
"count": batchesCompleted,
"error": "Failed to fetch mock data: " + error
};
res.json(resultObject);
}
)
}
} else {
// Fetch one set of sample data and then use for repeated batches of writes
requestJSON(docURL)
.then(
function(docs) {
// Build an array of popCollection calls (not being executed at this point)
var taskList = [];
for (i = 0; i < requestBody.numberDocs; i++) {
taskList.push(database.popCollection(requestBody.collectionName, docs))
}
// Promise.all executes all of the tasks in the provided array asynchronously (i.e.
// they can run in parallel).
var allPromise = Promise.all(taskList);
allPromise
.then(
function(result) {
database.close();
resultObject = {
"success": true,
"count": requestBody.numberDocs,
"error": ""
};
res.json(resultObject);
},
function(error) {
database.close();
resultObject = {
"success": false,
"count": 0, // If some writes succeeded then the real count may be > 0
"error": "Failed to write data: " + error
};
res.json(resultObject);
}
)
},
function(error) {
database.close();
resultObject = {
"success": false,
"count": 0,
"error": "Failed to fetch mock data: " + error
};
res.json(resultObject);
}
)
}
},
function(error) {
resultObject = {
"success": false,
"count": 0,
"error": "Failed to connect to database: " + error
};
res.json(resultObject);
}
)
})
router.post('/sampleDocs', function(req, res, next) {
/* Request from client to read a sample of the documents from a collection; the request
should be of the form:
{
MongoDBURI: string; // Connect string for MongoDB instance
collectionName: string;
numberDocs: number; // How many documents should be in the result set
}
The response will contain:
{
success: boolean;
documents: string; // Sample of documents from collection
error: string;
}
*/
var requestBody = req.body;
var database = new DB;
database.connect(requestBody.MongoDBURI)
.then(
function() {
// Returning will pass the promise returned by sampleCollection to
// the next .then in the chain
return database.sampleCollection(
requestBody.collectionName,
requestBody.numberDocs)
}) // No function is provided to handle the connection failing and so that
// error will flow through to the next .then
.then(
function(docs) {
return {
"success": true,
"documents": docs,
"error": ""
};
},
function(error) {
console.log('Failed to retrieve sample data: ' + error);
return {
"success": false,
"documents": null,
"error": "Failed to retrieve sample data: " + error
};
})
.then(
function(resultObject) {
database.close();
res.json(resultObject);
}
)
})
router.post('/countDocs', function(req, res, next) {
/* Request from client to count the number of documents in a
collection; the request should be of the form:
{
MongoDBURI: string; // Connect string for MongoDB instance
collectionName: string;
}
The response will contain:
{
success: boolean;
count: number; // The number of documents in the collection
error: string;
}
*/
var requestBody = req.body;
var database = new DB;
database.connect(requestBody.MongoDBURI)
.then(
function() {
return database.countDocuments(requestBody.collectionName)
})
.then(
function(count) {
return {
"success": true,
"count": count,
"error": ""
};
},
function(err) {
console.log("Failed to count the documents: " + err);
return {
"success": false,
"count": 0,
"error": "Failed to count the documents: " + err
};
})
.then(
function(resultObject) {
database.close();
res.json(resultObject);
})
})
function add(a, b) {
return a + b;
}
router.post('/updateDocs', function(req, res, next) {
/* Request from client to apply an update to all documents in a collection
which match a given pattern; the request should be of the form:
{
MongoDBURI: string; // Connect string for MongoDB instance
collectionName: string;
matchPattern: Object; // Filter to determine which documents should
// be updated (e.g. '{"gender": "Male"}'')
dataChange: Object; // Change to be applied to each matching change
// (e.g. '{"$set": {"mmyComment": "This is a
// man"}, "$inc": {"myCounter": 1}}')
threads: number; // How many times to repeat (in parallel) the operation
}
The response will contain:
{
success: boolean;
count: number; // The number of documents updated (should be the
// the number of documents matching the pattern
// multiplied by the number of threads)
error: string;
}
*/
var requestBody = req.body;
var database = new DB;
database.connect(requestBody.MongoDBURI)
.then(
function() {
// Build up a list of the operations to be performed
var taskList = []
for (var i=0; i < requestBody.threads; i++) {
taskList.push(database.updateCollection(
requestBody.collectionName,
requestBody.matchPattern,
requestBody.dataChange));
}
// Asynchronously run all of the operations
var allPromise = Promise.all(taskList);
allPromise
.then(
function(values) {
documentsUpdated = values.reduce(add, 0);
return {
"success": true,
"count": documentsUpdated,
"error": {}
};
},
function(error) {
console.log("Error updating documents" + error);
return {
"success": false,
"count": 0,
"error": "Error updating documents: " + error
};
}
)
.then(
function(resultObject) {
database.close();
res.json(resultObject);
}
)
},
function(error) {
console.log("Failed to connect to the database: " + error);
resultObject = {
"success": false,
"count": 0,
"error": "Failed to connect to the database: " + error
};
res.json(resultObject);
}
);
})
router.post('/addDoc', function(req, res, next) {
/* Request from client to add a sample of the documents from a collection; the request
should be of the form:
{
collectionName: string,
document: JSON document,
}
The response will contain:
{
success: boolean,
error: string
}
*/
var requestBody = req.body;
var database = new DB;
database.connect(config.makerMongoDBURI)
.then(
function() {
// Returning will pass the promise returned by addDoc to
// the next .then in the chain
return database.addDocument(requestBody.collectionName, requestBody.document)
}) // No function is provided to handle the connection failing and so that
// error will flow through to the next .then
.then(
function(docs) {
return {
"success": true,
"error": ""
};
},
function(error) {
console.log('Failed to add document: ' + error);
return {
"success": false,
"error": "Failed to add document: " + error
};
})
.then(
function(resultObject) {
database.close();
res.json(resultObject);
}
)
})
router.post('/checkIn', function(req, res, next) {
/* Request from client to add a sample of the documents from a collection; the request
should be of the form:
{
venue,
date,
url,
location
}
The response will contain:
{
success: boolean,
error: string
}
*/
var requestBody = req.body;
var database = new DB;
database.connect(config.makerMongoDBURI)
.then(
function() {
var checkIn = {
venueName: requestBody.venue,
date: requestBody.date,
url: requestBody.url,
mapRef: requestBody.location
}
// Returning will pass the promise returned by addDoc to
// the next .then in the chain
return database.addDocument(config.checkinCollection, checkIn)
}) // No function is provided to handle the connection failing and so that
// error will flow through to the next .then
.then(
function(docs) {
return {
"success": true,
"error": ""
};
},
function(error) {
console.log('Failed to add document: ' + error);
return {
"success": false,
"error": "Failed to add document: " + error
};
})
.then(
function(resultObject) {
database.close();
res.json(resultObject);
}
)
})
router.get('/checkInCount', function(req, res, next) {
/* Request from client for the number of checkins
The response will contain:
{
success: boolean,
count: number,
error: string
}
*/
var requestBody = req.body;
var database = new DB;
database.connect(config.makerMongoDBURI)
.then(
function() {
// Returning will pass the promise returned by countDocuments to
// the next .then in the chain
return database.countDocuments(config.checkinCollection)
}) // No function is provided to handle the connection failing and so that
// error will flow through to the next .then
.then(
function(count) {
return {
"success": true,
"count": count,
"error": ""
};
},
function(error) {
console.log('Failed to count checkins: ' + error);
return {
"success": false,
"count": 0,
"error": "Failed to count checkins: " + error
};
})
.then(
function(resultObject) {
database.close();
res.json(resultObject);
}
)
})
router.get('/latestCheckIn', function(req, res, next) {
/* Request from client for the number of checkins
The response will contain:
{
success: boolean,
venue,
date,
url,
location
error: string
}
*/
var requestBody = req.body;
var database = new DB;
database.connect(config.makerMongoDBURI)
.then(
function() {
// Returning will pass the promise returned by mostRecentDocument to
// the next .then in the chain
return database.mostRecentDocument(config.checkinCollection)
}) // No function is provided to handle the connection failing and so that
// error will flow through to the next .then
.then(
function(doc) {
return {
"success": true,
"venue": doc.venueName,
"date": doc.date,
"url": doc.url,
"location": doc.mapRef,
"error": ""
};
},
function(error) {
console.log('Failed to find last checkin: ' + error);
return {
"success": false,
"venue": "",
"date": "",
"url": "",
"location": "",
"error": "Failed to find last checkin: " + error
};
})
.then(
function(resultObject) {
database.close();
res.json(resultObject);
}
)
})
module.exports = router;