forked from osmlab/ohauth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (56 loc) · 1.6 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
'use strict';
var ohauth = {};
ohauth.qsString = function (obj) {
return Object.keys(obj)
.sort()
.map(function (key) {
return ohauth.percentEncode(key) + '=' + ohauth.percentEncode(obj[key]);
})
.join('&');
};
ohauth.stringQs = function (str) {
return str
.split('&')
.filter(function (pair) {
return pair !== '';
})
.reduce(function (obj, pair) {
var parts = pair.split('=');
obj[decodeURIComponent(parts[0])] =
null === parts[1] ? '' : decodeURIComponent(parts[1]);
return obj;
}, {});
};
ohauth.rawxhr = function (method, url, data, headers, callback) {
var xhr = new XMLHttpRequest(),
twoHundred = /^20\d$/;
xhr.onreadystatechange = function () {
if (4 === xhr.readyState && 0 !== xhr.status) {
if (twoHundred.test(xhr.status)) callback(null, xhr);
else return callback(xhr, null);
}
};
xhr.onerror = function (e) {
return callback(e, null);
};
xhr.open(method, url, true);
for (var h in headers) xhr.setRequestHeader(h, headers[h]);
xhr.send(data);
return xhr;
};
ohauth.xhr = function (method, url, access_token, data, options, callback) {
var headers = (options && options.header) || {
'Content-Type': 'application/x-www-form-urlencoded',
};
headers.Authorization = 'Bearer ' + access_token;
return ohauth.rawxhr(method, url, data, headers, callback);
};
ohauth.percentEncode = function (s) {
return encodeURIComponent(s)
.replace(/\!/g, '%21')
.replace(/\'/g, '%27')
.replace(/\*/g, '%2A')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29');
};
module.exports = ohauth;