-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
75 lines (62 loc) · 1.88 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
"use strict";
let request = require("request");
let __slice = Array.prototype.slice;
/**
* Promisify a request method.
*
* @param {Function} fn
* @return {Function}
*/
let promisifyRequestMethod = function (fn) {
let context = this;
return function () {
let args = __slice.call(arguments); //Array.from(arguments) is not available.
return new Promise(function (resolve, reject) {
// Concatenate the callback manually to avoid array arguments from co.
return fn.apply(context, args.concat(function (err) {
if (err) {
reject(err);
} else {
resolve.apply(this, __slice.call(arguments, 1));
}
}));
});
}
};
/**
* Promisify a request function.
*
* @param {Function} request
* @return {Function}
*/
let promisifyRequest = function (request) {
let fn = promisifyRequestMethod(request);
// Regular request methods that don't need be promisified.
fn.jar = request.jar;
fn.cookie = request.cookie;
// Export the defaults method and return a promisified request instance.
fn.defaults = function () {
return promisifyRequest(request.defaults.apply(request, arguments));
};
// Export the forever agent method and return a promisified request instance.
fn.forever = function () {
return promisifyRequest(request.forever.apply(request, arguments));
};
// Attach all request methods.
["get", "patch", "post", "put", "head", "del"].forEach(function (method) {
fn[method] = promisifyRequestMethod.call(request, request[method]);
});
return fn;
};
/**
* Export a promisified request function.
*
* @type {Function}
*/
exports = module.exports = promisifyRequest(request);
/**
* Export the Request instance.
*
* @type {Function}
*/
exports.Request = request.Request;