forked from customerio/customerio-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
73 lines (62 loc) · 1.67 KB
/
request.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
const axios = require('axios').default;
const { Base64 } = require('js-base64');
const TIMEOUT = 10000;
class Request {
constructor(auth, defaults) {
if (typeof auth === 'object') {
this.apikey = auth.apikey;
this.siteid = auth.siteid;
this.auth = `Basic ${Base64.encode(`${this.siteid}:${this.apikey}`)}`;
} else {
this.appKey = auth;
this.auth = `Bearer ${this.appKey}`;
}
this.defaults = Object.assign(
{
timeout: TIMEOUT,
},
defaults,
);
this._axios = axios.create(this.defaults);
}
options(uri, method, data) {
const headers = {
Authorization: this.auth,
'Content-Type': 'application/json',
};
const body = data ? JSON.stringify(data) : null;
const options = { method, uri, headers, body };
if (!body) delete options.body;
return options;
}
handler(options) {
return new Promise((resolve, reject) => {
this._axios(options)
.then((response) => {
if (response.status == 200 || response.status == 201) {
resolve(response.data);
} else {
reject({
message: response.statusText || 'Unknown error',
statusCode: response.status,
response: response,
body: response.data,
});
}
})
.catch((error) => {
reject(error);
});
});
}
put(uri, data = {}) {
return this.handler(this.options(uri, 'PUT', data));
}
destroy(uri) {
return this.handler(this.options(uri, 'DELETE'));
}
post(uri, data = {}) {
return this.handler(this.options(uri, 'POST', data));
}
}
module.exports = Request;