UNPKG

1.38 kBJavaScriptView Raw
1/**
2 * helper to wait for all callbacks to complete; similar to `Promise.all`
3 * exposed to metrics object for unit tests
4 * @param {Array} requests
5 * @param {Function} handler
6 * @param {Function} callback
7 */
8exports.async_all = function(requests, handler, callback) {
9 var total = requests.length,
10 errors = null,
11 results = [],
12 done = function (err, result) {
13 if (err) {
14 // errors are `null` unless there is an error, which allows for promisification
15 errors = errors || [];
16 errors.push(err);
17 }
18 results.push(result);
19 if (--total === 0) {
20 callback(errors, results)
21 }
22 };
23
24 if (total === 0) {
25 callback(errors, results);
26 } else {
27 for(var i = 0, l = requests.length; i < l; i++) {
28 handler(requests[i], done);
29 }
30 }
31};
32
33/**
34 * Validate type of time property, and convert to Unix timestamp if necessary
35 * @param {Date|number} time - value to check
36 * @returns {number} Unix timestamp
37 */
38exports.ensure_timestamp = function(time) {
39 if (!(time instanceof Date || typeof time === "number")) {
40 throw new Error("`time` property must be a Date or Unix timestamp and is only required for `import` endpoint");
41 }
42 return time instanceof Date ? time.getTime() : time;
43};