/
core.js
executable file
·226 lines (194 loc) · 5.93 KB
/
core.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
var http = require('http'),
moment = require('moment'),
_ = require('underscore'),
md5 = require('MD5'),
querystring = require('querystring'),
url = require('url'),
apierror = require('./error');
var cfg = {
httpRealHost: 'gw.api.taobao.com',
httpRealPath: '/router/rest',
httpSandHost: 'gw.api.tbsandbox.com',
httpSandPath: '/router/rest',
httpsRealHost: 'eco.taobao.com',
httpsRealPath: '/router/rest',
httpsSandHost: 'gw.api.tbsandbox.com',
httpsSandPath: '/router/rest',
app_key: '',
app_secret: '',
sandbox: false,
session: ''
};
var core = module.exports = {
error: apierror,
config: function(config) {
_.extend(cfg, config);
},
/**
* low-level for call tao bao api
*
* @param {Object}
* httpArgs http arguments for call api
* <pre>
* {
* method : 'get', //http method - optional, default is get
* protocol: 'http' //http protocol(http or https) - optional, default is http
* sandbox: false //whether to call api in sandbox - optional, default is false
* }
* </pre>
*
* @param {Object}
* args api args need to call taobao api
* <pre>
* {
* // system arguments
* method : 'taobao.taobaoke.items.get', //api method - required
* timestamp: '2012-03-15 21:00:00', //time stamp - optional, default is the time when call the api
* format: 'json', //the result format - optional, default is json
* app_key: 'xxxx', //app key - required, config use init method or pass through here
* app_secret: 'xxxxx', //app secret - required, config use init method or pass through here
* v: '2.0', //api version - optional, default is 2.0
* sign_method: 'md5' //sign method - optional, default is md5, now only support md5
*
* // method specific arguments
*
* }
* </pre>
*
* @param {Function}
* callback function with parameters to get the result
*
* @returns {Array[search...]}
*/
call: function (httpArgs, args, callback) {
//compatiple with call (args, callback) signature
if (arguments.length == 2) {
callback = args;
args = httpArgs;
httpArgs = {};
}
args.method = args.method;
args.timestamp = args.timestamp || moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
args.format = args.format || 'json';
args.app_key = args.app_key || cfg.app_key;
args.app_secret = args.app_secret || cfg.app_secret;
args.v = args.v || '2.0';
args.sign_method = 'md5';
args.session = args.session || cfg.session;
if (!args.session) {
delete args.session;
}
args.sign = this.signArgs(args);
var params = '',
app_secret = args.app_secret;
delete args.app_secret;
params = querystring.stringify(args);
var host, path, protocol, httpMethod, sandbox;
protocol = (httpArgs.protocol || 'http').toLowerCase();
httpMethod = (httpArgs.method || 'get').toLowerCase();
sandbox = httpArgs.sandbox === true ? true : cfg.sandbox === true;
switch (protocol) {
case 'https':
host = sandbox ? cfg.httpsSandHost : cfg.httpsRealHost;
path = sandbox ? cfg.httpsSandPath : cfg.httpsRealPath;
break;
default:
host = sandbox ? cfg.httpSandHost : cfg.httpRealHost;
path = sandbox ? cfg.httpSandPath : cfg.httpsRealPath;
break;
}
var protocolProxy = protocol == 'https' ? require('https') : require('http');
var resData = '',
headers = {};
if (httpMethod == 'post') {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
var reqOpts = {
method: httpMethod,
host: host,
headers:headers,
path: path + (httpMethod == 'get' ? '?' + params : '')
};
var req = protocolProxy.request(reqOpts, function(res) {
if (res.statusCode != 200) {
callback && callback({error_response: {code: apierror.NETERROR.code, msg: apierror.NETERROR.msg, statusCode: res.statusCode}});
} else {
res.setEncoding('utf-8');
res.on('data', function(chunk){
resData += chunk;
});
res.on('end', function() {
try {
callback && callback(JSON.parse(resData));
} catch (e) {
callback && callback(resData);
}
})
}
});
req.on('error', function(e) {
callback && callback({error_response: {code: apierror.NETERROR.code, msg: e.message || apierror.NETERROR.msg}});
});
if (httpMethod == 'post') {
req.write(params);
}
req.end();
},
signArgs: function(args) {
var argArr = [];
for (var argName in args) {
if (argName != 'sign' && argName != 'app_secret') {
argArr.push(argName + args[argName]);
}
}
var c = args.app_secret + argArr.sort().join('') + args.app_secret;
return md5(c).toUpperCase();
},
callDefaultArg: function(defArg, httpArgs, args, callback) {
defArg = defArg || {};
httpArgs = httpArgs || {};
if (_.isFunction(httpArgs)) {
callback = httpArgs;
this.call(defArg, callback);
} else if (_.isFunction(args)) {
callback = args;
args = httpArgs;
_.extend(defArg, args);
this.call(defArg, callback);
} else if (_.isFunction(callback)) {
_.extend(defArg, args);
this.call(httpArgs, defArg, callback);
} else {
throw apierror.ARGINVALID;
}
},
generateApi: function(apiArr, defaultNamespace) {
apiArr = apiArr || [];
var api = {},
dotReg = /\.([a-z])/ig,
upperRep = function(all, letter) {
return letter.toUpperCase();
};
_.each(apiArr, function(apiObj) {
var method, defaultArg = {}, namespace = defaultNamespace || 'taobao';
if (typeof apiObj == 'string') {
method = apiObj;
} else {
method = apiObj.method;
namespace = apiObj.namespace || defaultNamespace || 'taobao';
defaultArg = apiObj.defaultArg;
}
var methodName = (namespace == 'taobao' ? method : namespace + '.' + method).replace(dotReg, upperRep);
api[methodName] = function (httpArgs, args, callback) {
var defArg = _.extend({
method: namespace + '.' + method
}, defaultArg);
core.callDefaultArg(defArg, httpArgs, args, callback);
};
});
return api;
},
getConfig: function () {
return cfg;
}
};