-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
85 lines (81 loc) · 2.23 KB
/
server.js
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
const axios = require('axios').default;
const http = require('http');
const https = require('https');
const defaultUrl = 'http://127.0.0.1:3000';
const defaultToken = 'DEMO';
const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });
class Server{
constructor(options){
this.srv = options.url ? options.url : defaultUrl;
this.token = options.token ? options.token : defaultToken;
if (this.srv.endsWith("/")) {
this.srv = this.srv.slice(0, -1);
}
}
async get(url) {
const headers = {
'X-Bunker-Token': this.token
};
const options = {
httpAgent, httpsAgent, headers
};
try {
return await axios.get(this.srv + url, options);
} catch (err) {
if (err.response.data.status) {
return {data: err.response.data};
}
return {data:{status:'error', message:err.response.data}};
}
}
async del(url) {
const headers = {'X-Bunker-Token': this.token};
const options = {
httpAgent, httpsAgent, headers
};
try {
return await axios.delete(this.srv + url, options);
} catch (err) {
if (err.response.data.status) {
return {data: err.response.data};
}
return {data:{status:'error', message:err.response.data}};
}
}
async post(url, data) {
const headers = {
'X-Bunker-Token': this.token,
'Content-Type': 'application/json;charset=UTF-8'
};
const options = {
httpAgent, httpsAgent, headers
};
try {
return await axios.post(this.srv + url, data, options);
} catch (err) {
if (err.response.data.status) {
return {data: err.response.data};
}
return {data:{status:'error', message:err.response.data}};
}
}
async put(url, data) {
const headers = {
'X-Bunker-Token': this.token,
'Content-Type': 'application/json;charset=UTF-8'
};
const options = {
httpAgent, httpsAgent, headers
};
try {
return await axios.put(this.srv + url, data, options);
} catch (err) {
if (err.response.data.status) {
return {data: err.response.data};
}
return {data:{status:'error', message:err.response.data}};
}
}
}
module.exports = Server;