-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathAxiosCall.js
More file actions
85 lines (78 loc) · 2.37 KB
/
AxiosCall.js
File metadata and controls
85 lines (78 loc) · 2.37 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
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
})
.catch(err => {
throw err;
});
// Normal callback behaviour if we have one
if (this.callbackSuccess) {
this.request
.then(response => {
let data = response.data;
if (data.error && this.callbackError) {
this.callbackError(data.error);
} else {
this.callbackSuccess(data.result);
}
}).catch(err => {
throw err;
});
}
// If we got a callbackError, we can catch the error and use it
if(this.callbackError){
this.request
.catch( error => {
this.callbackError('Request Failure', error);
}
);
}
else{
this.request.catch(err => {
throw err;
});
}
// Returning promise
return this.request;
}
}
exports.default = AxiosCall;