-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
102 lines (90 loc) · 2.25 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
'use strict';
var _ = require('lodash');
var vow = require('vow');
var Queue = require('vow-queue');
var Feature = require('../../storage/model/feature');
/**
* Creates GeoJSON Feature type Point.
* @function
* @name createFeature
* @returns {Object}
*/
exports.createFeature = function () {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [ _.random(-180, 180 - 1e-10, true), _.random(-85, 85, true) ]
},
properties: {
balloonContent: 'The quick brown fox jumps over the lazy dog',
hintContent: 'The quick brown fox jumps over the lazy dog'
}
};
};
/**
* Creates GeoJSON Features and save them to MongoDB.
* @function
* @name saveFeatures
* @param {Number} num Number of Features to create
* @returns {Object}
*/
exports.saveFeatures = function (num) {
var queue = new Queue({ weightLimit : 100 });
var tasks = [];
var enqueue = function (task) {
tasks.push(queue.enqueue(task, { priority: 1, weight: 1 }));
};
var createTask = function (i) {
return function () {
var defer = vow.defer();
var feature = new Feature(exports.createFeature());
feature.save(function (err, feature) {
defer.notify('saving feature: ' + i);
if(err) {
defer.reject(err);
}
else {
defer.resolve(feature._id + '');
}
});
return defer.promise();
};
};
var getProgress = function (num) {
return Math.round(num * 100 / tasks.length);
};
for(var i = 0; i < num; i++) {
enqueue(createTask(i));
}
queue.start();
return vow.allResolved(tasks).then(function (results) {
var features = [], errors = [];
results.forEach(function (promise, index) {
var value = promise.valueOf();
if(promise.isFulfilled()) {
features.push(value);
}
else {
errors.push({
index: index,
reason: value
});
}
});
return {
result: {
"features": features.length
},
errors: errors
};
})
.progress(function (message) {
var stats = queue.getStats();
return {
message: message,
processed: getProgress(stats.processedTasksCount),
processing: getProgress(stats.processingTasksCount)
};
});
};