-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
80 lines (71 loc) · 1.82 KB
/
index.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
const fetch = require('node-fetch');
class MyAdminAPI {
constructor({
username = null,
password = null,
apiKey = null,
sessionId = null,
uri = null,
}) {
if (!username) {
throw new Error('Must supply username');
}
if (!password && !sessionId && !apiKey) {
throw new Error('Must supply password OR sessionId and apiKey');
}
this.serverUrl = uri || 'https://myadminapi.geotab.com/v2/MyAdminApi.ashx';
this.credentials = {
username,
password,
apiKey,
sessionId,
};
}
async callAsync(method, params) {
if (!method) {
throw new Error('Must provide method');
}
if (!params) {
params = {};
}
const result = await this.post(method, {
...params,
apiKey: this.credentials.apiKey,
sessionId: this.credentials.sessionId,
});
return result;
}
async post(method, params) {
const body = JSON.stringify({
id: -1,
method,
params,
});
const data = await fetch(this.serverUrl, {
method: 'POST',
body,
headers: { 'Content-Type': 'application/json' },
}).then((res) => res.json());
if (data.error && data.error.errors) {
const error = new Error(data.error.message);
error.name = data.error.errors[0].name;
error.code = data.error.code;
throw error;
}
return data.result;
}
async authenticateAsync() {
if (!this.credentials.password) {
throw new Error('Must supply password for authenticate');
}
const params = {
username: this.credentials.username,
password: this.credentials.password,
};
const result = await this.post('Authenticate', params);
this.credentials.apiKey = result.userId;
this.credentials.sessionId = result.sessionId;
return result;
}
}
module.exports = MyAdminAPI;