This repository has been archived by the owner on Nov 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
APIClient.ts
162 lines (132 loc) · 4.54 KB
/
APIClient.ts
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import type { Logging } from 'homebridge';
import request from 'request';
import { PUBLIC_API_URI, AUTH_URI } from '../config';
import { Location } from './Location';
import { WebhookAction } from './WebhookData';
export class APIClient {
constructor(
private log: Logging,
private grantFormParameters: Record<string, string>,
private updateReachability: (reachable: boolean) => void,
) {
}
private token: string | undefined;
private timeoutUntil: Date | undefined;
// https://nellopublicapi.docs.apiary.io/#reference/0/locations-collection/open-door
async openLocation(location: Location): Promise<void> {
await this.request(
'PUT',
`/locations/${location.location_id}/open/`,
);
}
// https://nellopublicapi.docs.apiary.io/#reference/0/locations-collection/list-locations
async getLocations(): Promise<Location[]> {
const response = await this.request<{ data: Location[] }>('GET', '/locations/');
if (!response?.data) {
throw new Error(`Could not get locations from response: ${JSON.stringify(response)}`);
}
return response.data;
}
// https://nellopublicapi.docs.apiary.io/#reference/0/locations-collection/add-/-update-webhook
async updateWebhook(location: Location, uri: string, hmacKey?: string): Promise<void> {
return this.request(
'PUT',
`/locations/${location.location_id}/webhook/`,
{
url: uri,
actions: Object.values(WebhookAction),
...(hmacKey ? { key: hmacKey } : undefined),
},
);
}
private async request<TResponse = undefined, TBody = undefined>(
method: 'GET' | 'POST' | 'PUT',
path: string,
body: TBody | undefined = undefined,
): Promise<TResponse> {
const url = `${PUBLIC_API_URI}${path}`;
const logPart = `${method} ${url}`;
this.log(`START Request: ${logPart}`);
if (!this.token) {
this.log('Not signed in, requesting sign-in');
await this.signIn();
}
const response = await this.baseRequest<TResponse, TBody>(method, url, body);
this.log(`COMPLETE Request: ${logPart}`);
return response;
}
private setToken(token: string): void {
this.token = token;
}
private resetToken(): void {
this.token = undefined;
}
private async signIn(): Promise<void> {
this.resetToken();
// https://nelloauth.docs.apiary.io/#reference/0/token/
const response = await this.baseRequest<{
scope: string,
token_type: string,
access_token: string,
refresh_token?: string,
}, undefined>(
'POST',
`${AUTH_URI}/oauth/token/`,
undefined,
this.grantFormParameters,
);
if (!response?.token_type || !response?.access_token) {
this.log.error(`Error while signing in. Could not get access token from response: ${JSON.stringify(response)}`);
return;
}
this.setToken(`${response.token_type} ${response.access_token}`);
}
private async baseRequest<TResponse, TBody>(
method: 'GET' | 'POST' | 'PUT',
path: string,
body: TBody | undefined = undefined,
form: Record<string, string> | undefined = undefined,
): Promise<TResponse> {
const now = new Date().valueOf();
const waitUntil = this.timeoutUntil?.valueOf();
if (waitUntil && now < waitUntil) {
const waitTime = waitUntil - now;
this.log.warn(`Rate-limited, waiting ${waitTime / 1000} seconds`);
await new Promise((resolve) => { setTimeout(resolve, waitTime); });
}
return new Promise((resolve, reject) => {
request({
uri: path,
method,
headers: {
Authorization: this.token,
},
form,
json: body ?? true,
}, (error, response, responseBody) => {
const message = `API error path=${path}`;
if (error) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
this.log.error(`${message}, error=${error}`);
reject(error);
return;
}
if (response.statusCode !== 200) {
const msgWithResponse = `${message}, status_code=${response.statusCode}, response=${JSON.stringify(responseBody)}`;
if (response.statusCode === 429) {
// 1 minute
this.timeoutUntil = new Date(new Date().valueOf() + 1 * 60 * 1000);
} else {
this.updateReachability(false);
this.resetToken();
}
this.log.warn(msgWithResponse);
reject(new Error(msgWithResponse));
return;
}
this.updateReachability(true);
resolve(responseBody);
});
});
}
}