-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapi_request.js
88 lines (75 loc) · 2.1 KB
/
api_request.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
function ApiRequest(opts) {
this.using(opts);
}
/**
* Serialize a set of key/value pairs into a POST data string
*
* @param {object} obj Key/value pairs
* @param {string} prefix String to prefix parameters with
* @return {string}
*/
ApiRequest.serializePostData = function(obj, prefix) {
var str = [],
v;
if (Array.isArray(obj)) {
if (!prefix) {
throw "You can't serialize a plain array: " + JSON.stringify(obj);
}
for (var i = 0; i < obj.length; i++) {
v = obj[i];
var k = encodeURIComponent(prefix) + "%5B%5D" ;
if(!isScalar(v)) {
throw "You can't serialize nested objects: " + JSON.stringify(obj);
}
str.push(k + "=" + encodeURIComponent(v));
}
} else {
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? encodeURIComponent(prefix) + "%5B" + encodeURIComponent(p) + "%5D" : p;
v = obj[p];
str.push((v && typeof v == "object") ?
ApiRequest.serializePostData(v, p) :
k + "=" + encodeURIComponent(v));
}
}
}
return str.join("&");
};
ApiRequest.prototype = {
qs: '',
/**
* Add query parameters to url
*
* @param {string} qs Query string to append to URL
*/
addQueryParams: function(qs) {
this.qs += (this.qs ? '&' : '') + qs;
},
/**
* Takes an options object and updates the current request
*
* @param {object} opts Options to apply to request
* @return this
*/
using: function(opts) {
opts = opts || {};
this.headers = Object.assign({}, this.headers, opts.headers);
this.post = Object.assign({}, this.post, opts.post);
this.method = opts.method || this.method || 'GET';
this.proto = opts.proto || this.proto || 'https';
this.baseUrl = opts.baseUrl || this.baseUrl || '';
this.url = opts.url || this.url || '';
this.path = opts.path || this.path || '';
return this;
},
/**
* Builds an URL based off of the options provided
*
* @return {string}
*/
buildUrl: function() {
var url = this.url || (this.proto + '://' + this.baseUrl + this.path);
return url + (this.qs ? ('?' + this.qs) : '');
}
}