-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
69 lines (56 loc) · 1.44 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
/**
* Module dependencies
*/
var debug = require('debug')('superagent:pool')
var qs = require('querystring')
/**
* Idempotent Methods
*/
var idempotent = /^(GET|HEAD|OPTIONS)$/
/**
* Export `superagent-pool`
*/
module.exports = pool
/**
* Initialize the `pool`
*
* @param {Superagent} superagent
* @return {Superagent}
*/
function pool (superagent) {
var end = superagent.Request.prototype.end
var pending = {}
// Monkey-path end
superagent.Request.prototype.end = function (fn) {
if (!idempotent.test(this.method)) return end.apply(this, arguments)
var key = serialize(this)
// already a request out, wait till it's response
if (pending[key]) {
debug('%s already requested, waiting for another request', key)
pending[key]
.once('response', function(res) { fn(null, res) })
.once('error', function(err) { fn(err) })
} else {
// first request with this url, make the request with this instance
pending[key] = this
end.call(this, function (err, res) {
debug('%s finished up', key)
delete pending[key]
return fn(err, res)
})
}
// return instance that is requesting
return pending[key]
}
return superagent
}
/**
* Serialize the request
*
* @param {Object} request
* @return {String}
*/
function serialize (request) {
var query = qs.stringify(request.qs)
return request.method + ' ' + request.url + (query ? '?' + query : '')
}