-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsuperagent-queue.js
111 lines (89 loc) · 1.69 KB
/
superagent-queue.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
/**
* Module dependencies.
*/
var superagent = require('superagent');
/**
* Module exports.
*/
module.exports = extend;
/**
* Installs the `queue` extension to superagent.
*
* @param {Object} superagent module
* @api public
*/
function extend(sa){
var Request = sa.Request;
/**
* Queues.
*/
var queues = {};
var running = {};
/**
* `queue` method.
*
* @param {String} name of the queue
* @return {Request} for chaining
* @api public
*/
Request.prototype.queue = function(name){
this.queueName = name;
return this;
};
/**
* Reference to original `end`.
*/
var oldEnd = Request.prototype.end;
/**
* Checks for queued requests.
*
* @api private
*/
function unqueue(name){
var item = queues[name].shift();
if (!item) {
delete queues[name];
return;
}
var obj = item[0];
var fn = item[1];
// immutable .length hack :\
if (!fn) {
oldEnd.call(obj, function(){
unqueue(name);
});
} else if (fn.length == 1) {
oldEnd.call(obj, function(res){
fn && fn(res);
unqueue(name);
});
} else {
oldEnd.call(obj, function(err, res){
fn && fn(err, res);
unqueue(name);
});
}
}
/**
* Overrides `end` method to defer calls.
*
* @api private
*/
Request.prototype.end = function(fn){
var queue = this.queueName;
if (queue) {
if (!queues[queue]) {
queues[queue] = [[this, fn]];
unqueue(queue);
} else {
queues[queue].push([this, fn]);
}
} else {
oldEnd.call(this, fn);
}
};
};
/**
* Extends the built-in dependency.
*/
extend(superagent);