api.js
2.41 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
const _ = require('lodash');
const Context = require('./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(url, data, options) {
let params = _.merge({
url,
headers: {
'Content-Type': 'application/json'
}
}, options);
if (options.method === 'get') {
params.qs = data;
} else {
params.body = JSON.stringify(data);
}
return request(params, (error, response) => {
if (!error) {
logger.info(`api call ${response.statusCode} [${response.request.method}] ${response.request.href} ${response.request.body}`); // eslint-disable-line
}
});
}
_request(options) {
options = Object.assign(options, {
resolveWithFullResponse: true
});
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} ${err.response.body || ''}`);
} else {
logger.error(`api call ${err}`);
}
return Promise.reject(API_INTERNAL_ERROR);
});
}
}
module.exports = Api;