api.js
2.21 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
const Context = require('./context');
const request = require('request');
const qs = require('querystring');
const _ = require('lodash');
const config = global.yoho.config;
const logger = global.yoho.logger;
const API_ERROR = {
code: 0,
message: '网络异常'
};
const API_INTERNAL_ERROR = {
code: 500,
message: '服务器错误'
};
class Api extends Context {
constructor() {
super();
}
get(url, data, headers) {
this.logGet(url, data);
return this.parse(() => {
return request.get({
url,
qs: data,
headers
});
});
}
logGet(url, data) {
logger.info('api call [GET]', url + '?' + qs.stringify(data));
}
post(url, data, headers) {
this.logPost(url, data);
return this.parse(() => {
return request.post({
url,
form: data,
headers
});
});
}
logPost(url, data) {
if (_.isString(data)) {
logger.info('api call [POST]', url + '?' + data);
} else {
logger.info('api call [POST]', url + '?' + qs.stringify(data));
}
}
upload() {
}
download() {
}
parse(req) {
return new Promise((resolve, reject) => {
let buffers = [], response;
req()
.on('error', error => {
if (error) {
return reject(API_ERROR);
}
})
.on('data', (chunk) => {
buffers.push(chunk);
})
.on('response', (res) => {
response = res;
})
.on('end', () => {
console.log(response.length);
if (buffers) {
// TODO 判断文件
try {
let jsonData = JSON.parse(buffers.toString('utf-8'));
return resolve(jsonData);
} catch (error) {
return reject(API_INTERNAL_ERROR);
}
}
return reject(API_INTERNAL_ERROR);
});
});
}
}
module.exports = Api;