-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (75 loc) · 2.42 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
'use strict';
var vm = require('vm');
var request = require('then-request');
var Promise = require('promise');
module.exports = pquest;
function pquest(method, url, options, callback) {
var callbackName;
var result = Promise.resolve(null).then(function () {
// check types of arguments
if (typeof method !== 'string') {
throw new TypeError('The method must be a string.');
}
if (typeof url !== 'string') {
throw new TypeError('The URL/path must be a string.');
}
if (typeof options === 'function') {
callback = options;
options = {};
}
if (options === null || options === undefined) {
options = {};
}
if (typeof options !== 'object') {
throw new TypeError('Options must be an object (or null).');
}
if (typeof callback !== 'function') {
callback = undefined;
}
if (options.skipJsonpOnServer) {
return request(method, url, options).getBody('utf8').then(JSON.parse);
}
if (options.body) {
throw new TypeError('JSONP does not support requests that have bodies');
}
if (options.headers) {
throw new TypeError('JSONP does not support requests that specify headers');
}
if (options.followRedirects === false) {
throw new TypeError('JSONP does not support requests that do not follow redirects');
}
options.qs = options.qs || {};
if (options.json) {
Object.keys(options.json).forEach(function (key) {
options.qs[key] = options.json[key];
});
delete options.json;
}
callbackName = options.callbackName || 'then_jsonp_0';
if (options.callbackParameter !== false) {
options.qs[options.callbackParameter || 'callback'] = callbackName;
}
if (method.toLowerCase() !== 'get') {
options.qs[options.methodParameter || 'method'] = method;
}
return request('get', url, options).getBody('utf8');
}).then(function (body) {
if (options.skipJsonpOnServer) return body;
var sandbox = {};
var result, called;
sandbox[callbackName] = function (res) {
if (called) {
throw new Error('JSONP callback called multiple times');
}
result = res;
called = true;
};
vm.runInNewContext(body, sandbox);
if (!called) throw new Error('JSONP timed out');
return result;
});
result.getBody = function () {
return result.then(function (res) { return res.getBody(); });
};
return result.nodeify(callback);
}