forked from opentable/superagent-es6-promise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (61 loc) · 1.76 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
// From https://gist.github.com/epeli/11209665
var Promise = require("es6-promise").Promise;
// So you can `var request = require("superagent-es6-promise")`
var superagent = module.exports = require("superagent");
var Request = superagent.Request;
// Create custom error type.
// Create a new object, that prototypally inherits from the Error constructor.
function SuperagentPromiseError(message) {
this.name = 'SuperagentPromiseError';
this.message = message || 'Bad request';
}
SuperagentPromiseError.prototype = new Error();
SuperagentPromiseError.prototype.constructor = SuperagentPromiseError;
/**
* @namespace utils
* @class Superagent
*/
/**
*
* Add promise support for superagent/supertest
*
* Call .promise() to return promise for the request
*
* @method then
* @return {Promise}
*/
Request.prototype.promise = function() {
var req = this;
var error;
return new Promise(function(resolve, reject) {
req.end(function(err, res) {
if (typeof res !== "undefined" && res.status >= 400) {
var msg = 'cannot ' + req.method + ' ' + req.url + ' (' + res.status + ')';
error = new SuperagentPromiseError(msg);
error.status = res.status;
error.body = res.body;
error.res = res;
reject(error);
} else if (err) {
reject(new SuperagentPromiseError(err));
} else {
resolve(res);
}
});
});
};
/**
*
* Make superagent requests Promises/A+ conformant
*
* Call .then([onFulfilled], [onRejected]) to register callbacks
*
* @method then
* @param {function} [onFulfilled]
* @param {function} [onRejected]
* @return {Promise}
*/
Request.prototype.then = function() {
var promise = this.promise();
return promise.then.apply(promise, arguments);
};