-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
59 lines (56 loc) · 2.02 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
var request_api = require('./request_api');
var getApiResponseName = require('./util/getApiResponseName');
function TopClient(key, secret, endpoint, options) {
if (typeof endpoint === 'object' && !options) {
options = endpoint
endpoint = options.endpoint;
}
if (!options) options = {};
if (!endpoint) endpoint = 'https://eco.taobao.com/router/rest';
var useValidators = true, rawResponse = false;
if (typeof options.useValidators === 'boolean') useValidators = options.useValidators;
if (typeof options.rawResponse === 'boolean') rawResponse = options.rawResponse;
this.execute = function (method, args, type, callback) {
if (typeof type === 'function') {
callback = type;
type = null;
}
var piped = false;
var proc = Promise.resolve().then(function () {
if (piped) return;
return new Promise(function (f, r) {
if (useValidators) require('./validator')(method, args);
args = Object.assign({}, args, { method: method, app_key: key });
request_api(endpoint, args, secret, type, function (err, data) {
if (rawResponse) {
f(data);
return;
}
if (err) {
return r(err);
}
var responseName = getApiResponseName(method), response = data[responseName];
f(response);
});
});
}).then(function (response) {
if (typeof callback === 'function') callback(null, response);
return response;
}).catch(function (e) {
if (typeof callback === 'function') callback(e);
throw e;
});
if (typeof callback !== 'function') {
var result_stream = null;
proc.pipe = function(stream) {
piped = true;
if (useValidators) require('./validator')(method, args);
args = Object.assign({}, args, { method: method, app_key: key });
if (!result_stream) result_stream = request_api(endpoint, args, secret, type);
return result_stream.pipe(stream);
}
return proc;
}
}
}
module.exports = TopClient;