forked from lightsofapollo/superagent-promise
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
102 lines (86 loc) · 2.19 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
/**
* Promise wrapper for superagent
*/
var Promise = require('bluebird');
function wrap(superagent) {
/**
* Request object similar to superagent.Request, but with end() returning
* a promise.
*/
function PromiseRequest() {
superagent.Request.apply(this, arguments);
}
// Inherit form superagent.Request
PromiseRequest.prototype = Object.create(superagent.Request.prototype);
/** Send request and get a promise that `end` was emitted */
PromiseRequest.prototype.end = function(cb) {
var _super = superagent.Request.prototype.end;
var context = this;
return new Promise(function(accept, reject) {
_super.call(context, function(err, value) {
if (cb) {
cb(err, value);
}
if (err) {
return reject(err);
}
accept(value);
});
});
};
/**
* Request builder with same interface as superagent.
* It is convenient to import this as `request` in place of superagent.
*/
var request = function(method, url) {
return new PromiseRequest(method, url);
};
request.wrap = wrap;
/** Helper for making a get request */
request.get = function(url, data) {
var req = request('GET', url);
if (data) {
req.query(data);
}
return req;
};
/** Helper for making a head request */
request.head = function(url, data) {
var req = request('HEAD', url);
if (data) {
req.send(data);
}
return req;
};
/** Helper for making a delete request */
request.del = function(url) {
return request('DELETE', url);
};
/** Helper for making a patch request */
request.patch = function(url, data) {
var req = request('PATCH', url);
if (data) {
req.send(data);
}
return req;
};
/** Helper for making a post request */
request.post = function(url, data) {
var req = request('POST', url);
if (data) {
req.send(data);
}
return req;
};
/** Helper for making a put request */
request.put = function(url, data) {
var req = request('PUT', url);
if (data) {
req.send(data);
}
return req;
};
// Export the request builder
return request;
}
module.exports = wrap(require('superagent'));