-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.js
126 lines (109 loc) · 2.79 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
* Promise wrapper for superagent
*/
function wrap(superagent, Promise) {
/**
* 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 _end = superagent.Request.prototype.end;
var self = this;
return new Promise(function(accept, reject) {
_end.call(self, function(err, response) {
if (cb) {
cb(err, response);
}
if (err) {
err.response = response;
reject(err);
} else {
accept(response);
}
});
});
};
/** Provide a more promise-y interface */
PromiseRequest.prototype.then = function(resolve, reject) {
var _end = superagent.Request.prototype.end;
var self = this;
return new Promise(function(accept, reject) {
_end.call(self, function(err, response) {
if (err) {
err.response = response;
reject(err);
} else {
accept(response);
}
});
}).then(resolve, reject);
};
/**
* 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);
};
/** Helper for making an options request */
request.options = function(url) {
return request('OPTIONS', url);
}
/** 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 get request */
request.get = function(url, data) {
var req = request('GET', url);
if (data) {
req.query(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;
};
/** 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 delete request */
request.del = function(url, data) {
var req = request('DELETE', url);
if (data) {
req.send(data);
}
return req;
};
// Export the request builder
return request;
}
module.exports = wrap;