/
index.js
115 lines (87 loc) · 2.21 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
var qs = require('querystring');
var debug = require('debug')('oauth-request');
var request = require('request');
var OAuth = require('oauth-1.0a');
module.exports = OAuthRequest;
function OAuthRequest(opt) {
if(!(this instanceof OAuthRequest)) {
return new OAuthRequest(opt);
}
this.token = opt.token || {};
this.oauth = OAuth(opt);
this._log('#init', this);
}
/**
* debug
*
* @api private
*/
OAuthRequest.prototype._log = debug;
/**
* set oauth token
* @param {String/Object} token
*/
OAuthRequest.prototype.setToken = function(token) {
this._log('#setToken', token);
if(typeof token === 'string') {
return this.token.key = token;
}
//object
return this.token = token;
};
OAuthRequest.prototype._validate = function(opt) {
if(typeof opt == 'string') {
return {url: opt};
}
if(!(opt.url)) {
throw new Error('url is required');
}
return opt;
};
OAuthRequest.prototype.get = function(opt, callback) {
opt = this._validate(opt);
var request_data = {
url: opt.url,
method: 'GET',
data: opt.qs
};
//override
opt.qs = this.oauth.authorize(request_data, this.token);
opt.method = request_data.method;
if(!callback) {
return request(opt);
}
this._log('#get', opt);
return request(opt, callback);
};
OAuthRequest.prototype.post = function(opt, callback) {
opt = this._validate(opt);
var request_data = {
url: opt.url,
method: 'POST',
data: opt.form
};
//override
opt.body = qs.stringify(this.oauth.authorize(request_data, this.token))
.replace(/\!/g, "%21")
.replace(/\*/g, "%2A")
.replace(/\'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29");
opt.method = request_data.method;
if(opt.headers) {
opt.headers['content-type'] = 'application/x-www-form-urlencoded';
} else {
opt.headers = {
'content-type': 'application/x-www-form-urlencoded'
};
}
//delete
delete opt.form;
delete opt.oauth;
this._log('#post', opt);
if(!callback) {
return request(opt);
}
return request(opt, callback);
};