-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiiko-client.js
90 lines (78 loc) · 2.52 KB
/
iiko-client.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
86
87
88
89
90
'use strict'
const axios = require('axios').default;
class IikoClient {
#_api = {
address: null,
login: null,
baseURL: "api/1/"
};
#_client;
/**
*
* @param address {String} required address
* @param login {String} required login
*/
constructor(address, login) {
this.#_api.address = address;
this.#_api.login = login;
}
/**
*
* @returns {Promise<void>}
*/
async connect(){
try{
let result = await axios.post(`${this.#_api.address}${this.#_api.baseURL}access_token`, {
"apiLogin": this.#_api.login
});
this.#_client = axios.create({
baseURL: `${this.#_api.address}${this.#_api.baseURL}`,
timeout: 1000,
headers: {'Authorization': `Bearer ${result.data.token}`}
});
}catch (err){
throw Error(err);
}
}
/**
*
* @param method {String} required http request method iiko API tells you to use for given endpoint
* @param endpoint {String} required endpoint which you are trying to reach (those can be found in iiko API documentation)
* @param query {String} optional query string
* @param options {Object} optional options (request body)
* @param retry {Boolean} optional property used internally to retry request if token Bearer token expired.
* @returns {Promise<*>}
*/
async request(method, endpoint, query = "", options, retry = true){
if(!this.#_client){
try{
await this.connect();
let result = await this.request(method, endpoint, query = "", options, retry = false);
return result;
}catch (err){
throw Error(err);
}
}
try{
let result = await this.#_client[method](`${endpoint}?${query}`, options);
return result.data;
}catch (err){
if (err.response) {
if(retry){
try{
await this.connect();
let result = await this.request(method, endpoint, query = "", options, retry = false);
return result;
}catch (err){
throw Error(err);
}
}else{
throw Error(err);
}
}else{
throw Error(err);
}
}
}
}
module.exports = IikoClient;