-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.ts
322 lines (268 loc) · 8.66 KB
/
request.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/**
* Module defines generic requests.
*/
"use strict";
import {Buffer} from "buffer";
import fetch, {Headers, Response} from "cross-fetch";
const API_PATH: string = "api";
const FETCH_TIMEOUT_S: number = 30;
type Method = "GET" | "POST";
interface FetchInit {
method: Method;
// @ts-ignore
headers?: Headers;
body?: any;
}
interface FetchWithTimeoutOptions {
init?: FetchInit;
timeoutS?: number;
}
interface ApiRequestInit {
username: string;
password: string;
url: string;
apiVersion: string;
}
interface SendOptions {
timeoutS?: number;
}
interface JsonErrorResponse {
message: string;
}
class TimeoutError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, TimeoutError.prototype);
}
}
class UnknownSecretError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, UnknownSecretError.prototype);
}
}
class NotFoundError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, NotFoundError.prototype);
}
}
class NotAuthorizedError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, NotAuthorizedError.prototype);
}
}
class RateLimitedError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, RateLimitedError.prototype);
}
}
class InternalServerError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, InternalServerError.prototype);
}
}
/**
* Join up the parameters in the dict to conform to
* application/x-www-form-urlencoded encoding.
*
* @param data dictionary of parameters
* @returns encoded data
*/
function urlEncodeDict(data: object): string {
const parameters: string[] = [];
for (const key in data) {
if (data.hasOwnProperty(key)) {
const encodedKey: string = encodeURIComponent(key);
const encodedValue: string = encodeURIComponent(data[key]);
const parameter: string = [encodedKey, encodedValue].join("=");
parameters.push(parameter);
}
}
return parameters.join("&");
}
/**
* Execute a request using the fetch API and raise an exception if an timeout
* occurred.
*
* @param url request url - passed to fetch
* @param options fetch options - passed to fetch
* @returns response object
* @throws error on timeout and if fetch fails
*/
async function fetchWithTimeout(
url: string,
// TODO Promise should actually be type Response, but this doesn't work
options?: FetchWithTimeoutOptions): Promise<any> {
let fetchTimeout: number;
let init: FetchInit;
if (typeof options.timeoutS !== "undefined") {
fetchTimeout = options.timeoutS * 1000;
}
if (typeof options.init !== "undefined") {
init = options.init;
}
return new Promise((resolve: Function, reject: Function): void => {
let didTimeOut: boolean = false;
let timeout: any;
if (typeof fetchTimeout !== "undefined") {
timeout = setTimeout((): void => {
didTimeOut = true;
reject(new TimeoutError("Request timed out"));
},
fetchTimeout);
}
fetch(url, init)
// @ts-ignore
.then((response: Response): void => {
if (timeout) {
// Clear the timeout as cleanup
clearTimeout(timeout);
}
if (!didTimeOut) {
resolve(response);
}
})
.catch((error: any): void => {
// Rejection already happened with setTimeout
if (didTimeOut) {
return;
}
reject(error);
});
});
}
class ApiRequest {
protected path: string;
protected method: Method;
protected body?: any;
// @ts-ignore
private readonly headers: Headers;
private apiUrl: string;
/**
* Create a OTS API request.
*
* @abstract
* @constructor
* @param init request parameters
* @throws error if username, apiKey, url, or apiVersion not defined
*/
public constructor(init: ApiRequestInit) {
const authorization: string = (
"Basic " + Buffer.from(init.username + ":" + init.password)
.toString("base64"));
this.headers = new Headers();
this.headers.append("Authorization", authorization);
this.headers.append("Accept", "application/json");
this.headers.append("Content-Type", "application/x-www-form-urlencoded");
this.apiUrl = [init.url, API_PATH, init.apiVersion].join("/");
}
/**
* Send the request to the server and wait for the result.
*
* @param options send options
* @returns that returns a processed response object
* @throws error on failed request or timeout
*/
public async send(options?: SendOptions) {
const defaultOptions: SendOptions = {timeoutS: FETCH_TIMEOUT_S};
const [url, init] = this.prepare();
// @ts-ignore
const response: Response = await fetchWithTimeout(
url,
{init, ...defaultOptions, ...options});
if (!response.ok) {
if (response.status === 500) {
throw new InternalServerError(
`url="${url}", status=${response.status}, `
+ `message="${response.statusText}"`);
}
if (typeof response.headers === "undefined") {
throw new Error(
`url='${url}', status=${response.status}, `
+ `message='${response.statusText}', headers missing`);
}
const contentType: string = response.headers.get("Content-Type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then((data: JsonErrorResponse): void => {
let error: Error;
switch (data.message) {
case "Unknown secret":
error = new UnknownSecretError("Unknown secret");
break;
case "Not Found":
error = new NotFoundError("Metadata not found");
break;
case "Not authorized":
error = new NotAuthorizedError("Request not authorized");
break;
case "Apologies dear citizen! You have been rate limited.":
error = new RateLimitedError("You have been rate limited.");
break;
default:
error = new Error(
`url="${url}", status=${response.status}, `
+ `message="${data.message}"`);
}
throw error;
});
} else {
let error: Error = null;
switch(response.statusText) {
case "Not Found":
error = new NotFoundError("Path not found");
break;
default:
error = new Error(
`url="${url}", status=${response.status}, `
+ `message="${response.statusText}"`);
}
throw error;
}
}
const jsonResponse: object = await response.json();
return this.process(jsonResponse);
}
/**
* Prepare an api request.
*
* @returns of format [url, init]
* @throws error if path or method not set
*/
protected prepare(): any[] {
const url: string = [this.apiUrl, this.path].join("/");
const init: FetchInit = {
headers: this.headers,
method: this.method,
};
if (this.method !== "GET" && this.body) {
init.body = this.body;
}
return [url, init];
}
/**
* Process the api request.
*
* @static
* @param response object received from the request
* @returns processed response object
*/
protected process(response: object): any {
return response;
}
}
export {
TimeoutError,
UnknownSecretError,
NotFoundError,
NotAuthorizedError,
RateLimitedError,
InternalServerError,
Method,
ApiRequestInit,
urlEncodeDict,
ApiRequest
}