api.js
2.62 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
const Context = require('../framework/context');
const rp = require('request-promise');
const request = require('request');
const logger = global.yoho.logger;
const API_INTERNAL_ERROR = {
code: 500,
message: '服务器错误'
};
class Api extends Context {
get(url, data, headers) {
return this._request({
url,
qs: data,
headers
});
}
post(url, data, headers) {
let defaultHeader = {
'Content-Type': 'application/json'
};
return this._request({
method: 'post',
url,
body: JSON.stringify(data),
headers: Object.assign(defaultHeader, headers)
});
}
upload(url, formData, headers) {
let defaultHeader = {
'Content-Type': 'application/json'
};
return this._request({
method: 'post',
url,
formData,
headers: Object.assign(defaultHeader, headers)
});
}
proxy(params) {
return request(params, (error, response) => {
if (!error) {
if (response && /^20\d/.test(response.statusCode)) {
logger.info(`api call ${response.statusCode} [${response.request.method}] ${response.request.href} ${response.request.body}`); // eslint-disable-line
} else {
let res = response.toJSON();
logger.error(`api call ${res.statusCode} [${res.request.method}] ${res.request.uri.href} ${params.qs || params.body || params.formData} ${res.body || ''}`); // eslint-disable-line
}
}
});
}
_request(options) {
options = Object.assign(options, {
resolveWithFullResponse: true,
timeout: 3000
});
return rp[options.method || 'get'](options).then(response => {
let jsonBody = JSON.parse(response.body);
let req = response.request;
logger.info(`api call ${response.statusCode} [${req.method}] ${req.uri.href} ${req.body || ''}`);
return jsonBody;
}).catch(err => {
if (err.statusCode) {
logger.error(`api call ${err.statusCode} [${err.options.method}]
${err.options.url} ${options.qs || options.body || options.formData} ${err.response.body || ''}`);
} else {
logger.error(`api call [${options.method || 'get'}] ${options.url}
${JSON.stringify(options.qs || options.body)} ${err}`);
}
return Promise.reject(API_INTERNAL_ERROR);
});
}
}
module.exports = Api;