api.js
6.73 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
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
227
228
229
230
231
232
233
234
235
236
237
/**
* 接口公共方法
* @author: xuqi<qi.xu@yoho.cn>
* @date: 2016/4/25
*/
'use strict';
const rp = require('request-promise');
const qs = require('querystring');
const md5 = require('md5');
const _ = require('lodash');
const log = require('./logger');
const cache = require('./cache');
const Timer = require('./timer');
const sign = require('./sign');
const config = require('../config/common');
const api = config.domains.api;
const serviceApi = config.domains.service;
const searchApi = config.domains.search;
// 错误返回
const API_BAD_RETSULT = {
code: 500,
message: 'API result is not JSON string or null.'
};
// 调用失败
const API_CALL_FAIL = {
code: 500,
message: 'Call API failed.'
};
// all 方法错误的传参
const API_ALL_METHOD_ERROR = 'the parameters of api all method should be Array!';
// 获取缓存数据失败
const SLAVE_CACHE_FAIL = 'get slave cache fail';
const MASTER_CACHE_FAIL = 'get master cache fail';
// 获取缓存数据成功
const SLAVE_CACHE_SUCCESS = 'get slave cache success';
const MASTER_CACHE_SUCCESS = 'get master cache success';
class Http {
constructor(baseUrl) {
this.ApiUrl = baseUrl;
}
/**
* 获取请求 ID
*/
_getReqId(options) {
return md5(`${options.url}?${qs.stringify(options.qs || options.form)}`);
}
/**
* 处理接口返回状态码
*/
_handleDataCode(data, code, url) {
let result = {};
code = code || 200;
if (_.toNumber(data.code) === _.toNumber(code)) {
_.unset(data, 'code');
_.forEach(data, (value, key) => {
_.set(result, key, value);
});
} else {
log.error(`API: ${url} return code not ${code}`);
}
return result;
}
/**
* 调用接口
*/
_requestFromAPI(options, param, reqId) {
const timer = new Timer();
const method = options.method || 'get';
timer.put('getApi');// 统计时间开始
return rp(options).then((result) => {
const duration = timer.put('getApi');// 统计时间结束
// 数据校验
if (!result) {
log.error(`error: ${API_BAD_RETSULT.message}`);
return Promise.reject(API_BAD_RETSULT);
}
// 处理返回数据状态码
if (param && param.code) {
result = this._handleDataCode(result, param.code, options.url);
}
// 写缓存, 否则返回 Slave 缓存服务器的数据
if (options.method === 'get' && config.useCache &&
param && param.cache) {
const cacheTime = _.isNumber(param.cache) ? param.cache : 60;
const catchErr = (err) => {
log.error(`cache: ${err.toString()}`);
};
reqId = reqId || this._getReqId(options);
cache.set(`apiCache:${reqId}`, result, cacheTime).catch(catchErr);
cache.setSlave(`apiCache:${reqId}`, result, 86400).catch(catchErr); // 二级缓存存储一天
}
log.info(`use: ${duration}ms for ${method} api: ${options.url}?${qs.stringify(options.qs)} `);
return result;
}).catch((err)=> {
const duration = timer.put('getApi');// 统计时间结束
log.error(`${method} api fail: use: ${duration}ms, code:${err.statusCode}, error: ${err.message}`);
log.error(`API: ${options.url}?${qs.stringify(options.qs)}`);
// 使用缓存的时候,读取二级缓存
if (config.useCache && param && param.cache) {
return this._requestFromCache(options, true);
}
return Promise.resolve(API_CALL_FAIL);
});
}
/**
* 读取缓存
* @param {[object]} options
* @param {[boolean]} slave true: 读取二级缓存
* @param {[object]} param 请求API处理参数
* @return {[type]}
*/
_requestFromCache(options, slave, param) {
const reqId = this._getReqId(options);
const getCache = slave ? cache.getFromSlave : cache.get;
log.info(`get ${slave ? 'slave' : 'master'} cache: ${reqId}, url: ${options.url}?${qs.stringify(options.qs)}`);
return getCache(`apiCache:${reqId}`).then((result) => {
if (!_.isNil(result)) {
try {
result = JSON.parse(result);
} finally {
log.info(slave ? SLAVE_CACHE_SUCCESS : MASTER_CACHE_SUCCESS);
return result;
}
}
// 读取缓存失败,并且不是二级缓存的时候,调用 API
if (!slave) {
return this._requestFromAPI(options, param, reqId);
}
}).catch(() => {
log.error(slave ? SLAVE_CACHE_FAIL : MASTER_CACHE_FAIL);
// 读取缓存失败,并且不是二级缓存的时候,调用 API
if (!slave) {
return this._requestFromAPI(options, param, reqId);
}
return Promise.resolve(API_CALL_FAIL);
});
}
/**
* 使用 get 请求获取接口
* @param {[string]} url
* @param {[object]} data
* @param {[object]} param 数据处理参数
* @return {[type]}
*/
get(url, data, param) {
const options = {
url: `${this.ApiUrl}${url}`,
qs: data.client_secret ? data : sign.apiSign(data),
json: true,
gzip: true,
timeout: 3000
};
// 从缓存获取数据
if (config.useCache && param && param.catch) {
return this._requestFromCache(options, false, param);
}
return this._requestFromAPI(options, param);
}
/**
* 使用 post 请求获取接口
* @param {[string]} url
* @param {[object]} data
* @param {[object]} param 数据处理参数
* @return {[type]}
*/
post(url, data, param) {
const options = {
url: `${this.ApiUrl}${url}`,
form: data.client_secret ? data : sign.apiSign(data),
method: 'post',
json: true,
timeout: 3000
};
return this._requestFromAPI(options, param);
}
all(list) {
if (_.isArray(list)) {
return Promise.all(list);
} else {
return Promise.reject(Error(API_ALL_METHOD_ERROR));
}
}
}
class API extends Http {
constructor() {
super(api);
}
}
class ServiceAPI extends Http {
constructor() {
super(serviceApi);
}
}
class SearchAPI extends Http {
constructor() {
super(searchApi);
}
}
exports.API = API;
exports.ServiceAPI = ServiceAPI;
exports.SearchAPI = SearchAPI;