-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathAxiosCall.js
More file actions
69 lines (63 loc) · 1.96 KB
/
AxiosCall.js
File metadata and controls
69 lines (63 loc) · 1.96 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
const axios = require('axios').default;
class AxiosCall {
constructor(method, server, params, callbackSuccess, callbackError){
this.config = {
headers: {
'content-type': 'application/json'
}
}
this.callbackSuccess = callbackSuccess;
this.callbackError = callbackError;
this.server = server;
this.body = {
method: method || '',
params: params
};
}
getCallUrl(){
let server = this.server || 'my.geotab.com';
let thisServer = server.replace(/\S*:\/\//, '').replace(/\/$/, '');
return 'https://' + thisServer + '/apiv1/';
}
encode(data){
let stringBody = JSON.stringify({
method: data.method || '',
params: data.params
})
return stringBody;
}
/**
* Sends axios request
* @param {int} timeout amount in milliseconds for timeout.
* options.timeout * 1000 is a good start
* Defaults to no timeout (0)
* @returns {Promise} Axios promise
*/
async send(timeout){
this.request = axios({
method: 'POST',
url: this.getCallUrl(),
data: this.encode(this.body),
headers: this.config.headers,
timeout: timeout * 1000
}).then(response => {
let data = response.data;
if(this.callbackSuccess){
if(data.error && this.callbackError){
this.callbackError(data.error);
} else {
this.callbackSuccess(data.result);
}
}
return response;
}).catch(error => {
if(this.callbackError){
this.callbackError('Request Failure', error.toJSON());
}
return error;
});
// Returning promise
return this.request;
}
}
exports.default = AxiosCall;