api.js
2.4 KB
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
/**
* 接口公共访问方法
* @author: xuqi<qi.xu@yoho.cn>
* @date: 2016/3/28
*/
'use strict';
var rp = require('request-promise'),
_ = require('lodash');
var errUtil = require('../util/error');
var sign = require('./sign');
var API_CONFIG = {
API_URL: 'http://testapi.yoho.cn:28078',
SERVICE_URL: 'http://testservice.yoho.cn:28077'
};
if (process.env.NODE_ENV === 'production') {
// 正式环境接口地址
API_CONFIG = {
API_URL: 'http://api.yoho.cn',
SERVICE_URL: 'http://service.yoho.cn'
};
}
class API {
// var api = new API(); 默认调用新版接口
// var api = new API('SERVICE_URL'); 服务调用方法
constructor(type) {
this.type = type || 'API_URL';
this.headers = {
'User-Agent': 'YOHO WEB NODE'
};
this.timeout = 5000;
this.server = API_CONFIG[this.type];
this.data = {};
if (this.type === 'API_URL') {
this.data.v = 7;
}
}
get(url, data) {
data = Object.assign(this.data, data);
if (this.type === 'API_URL') {
data = sign.apiSign(data);
}
return rp({
url: `${this.server}${url}`,
headers: this.headers,
timeout: this.timeout,
qs: data
}).catch(errUtil.apiError);
}
/**
* multi get
* @params: urls => Array[Object[url[string], data[object]]]
*/
multiGet(urls) {
var rps = [],
self = this;
_.forEach(urls, function(el) {
el.data = Object.assign(self.data, el.data);
if (self.type === 'API_URL') {
el.data = sign.apiSign(el.data);
}
rps.push(rp({
url: `${self.server}${el.url}`,
headers: self.headers,
timeout: self.timeout,
qs: el.data
}));
});
return Promise.all(rps).then((d) => {
return d;
}).catch(errUtil.apiError);
}
post(url, data) {
data = Object.assign(this.data, data);
if (this.type === 'API_URL') {
data = sign.apiSign(data);
}
return rp({
url: `${this.server}${url}`,
method: 'post',
headers: this.headers,
timeout: this.timeout,
form: data
}).catch(errUtil.apiError);
}
}
module.exports = API;