api.js
1.79 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
const Context = require('./context');
const request = require('request');
const config = global.yoho.config;
const API_ERROR = {
code: 0,
message: '网络异常'
};
const API_INTERNAL_ERROR = {
code: 500,
message: '服务器错误'
};
class Api extends Context {
constructor(domain = config.apiDomain.auth) {
super();
this.domain = domain;
}
get(url, data, headers) {
return this.parse(() => {
return request.get({
url,
qs: data,
headers,
});
});
}
post(url, data, headers) {
return this.parse(() => {
return request.post({
url,
form: data,
headers,
});
});
}
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;