-
Notifications
You must be signed in to change notification settings - Fork 180
/
client.ts
415 lines (369 loc) · 12.9 KB
/
client.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import fetch, { Response } from 'node-fetch';
import AbortError from 'node-fetch';
import { Auth, AuthInterface, AuthParams } from '@vonage/auth';
import {
ResponseTypes,
VetchResponse,
VetchOptions,
HTTPMethods,
ContentType,
VetchError,
} from '@vonage/vetch';
import { AuthenticationType } from './enums';
import * as transfomers from './transformers';
import debug from 'debug';
import { ConfigParams } from './types';
const log = debug('vonage:server-client');
export class Client {
/**
* Static property containing utility transformers.
*/
public static transformers = transfomers;
/**
* The type of authentication used for the client's requests.
*/
protected authType?: AuthenticationType = AuthenticationType.QUERY_KEY_SECRET;
/**
* The authentication instance responsible for generating authentication headers and query parameters.
*/
protected auth: AuthInterface;
/**
* Configuration settings for the client, including default hosts for various services and other request settings.
*/
protected config: ConfigParams;
/**
* Creates a new instance of the Client.
*
* @param {AuthInterface | AuthParams} credentials - The authentication credentials or an authentication instance.
* @param {ConfigParams} [options] - Optional configuration settings for the client.
*/
constructor(credentials: AuthInterface | AuthParams, options?: ConfigParams) {
this.auth = !Object.prototype.hasOwnProperty.call(
credentials,
'getQueryParams',
)
? new Auth(credentials)
: (credentials as AuthInterface);
this.config = {
restHost: options?.restHost || 'https://rest.nexmo.com',
apiHost: options?.apiHost || 'https://api.nexmo.com',
videoHost: options?.videoHost || 'https://video.api.vonage.com',
meetingsHost: options?.meetingsHost || 'https://api-eu.vonage.com',
proactiveHost: options?.proactiveHost || 'https://api-eu.vonage.com',
responseType: options?.responseType || ResponseTypes.json,
timeout: options?.timeout || null,
} as ConfigParams;
}
/**
* Adds the appropriate authentication headers or parameters to the request based on the authentication type.
*
* @param {VetchOptions} request - The request options to which authentication needs to be added.
* @return {Promise<VetchOptions>} - The request options with the added authentication.
*/
async addAuthenticationToRequest(
request: VetchOptions,
): Promise<VetchOptions> {
log(`adding ${this.authType || 'api key/secret'} to request`);
if (
!Object.values(AuthenticationType).includes(
this.authType as AuthenticationType,
)
) {
throw new Error('No authentication type set');
}
switch (this.authType) {
case AuthenticationType.BASIC:
request.headers = Object.assign({}, request.headers, {
Authorization: await this.auth.createBasicHeader(),
});
return request;
case AuthenticationType.JWT:
request.headers = Object.assign({}, request.headers, {
Authorization: await this.auth.createBearerHeader(),
});
return request;
}
if (this.authType === AuthenticationType.QUERY_KEY_SECRET) {
log(`adding parameters to query string`);
request.params = {
...(request.params ? request.params : {}),
...(await this.auth.getQueryParams({})),
};
return request;
}
if (typeof request.data === 'string') {
throw new Error('Cannot append auth parameters to body');
}
const authParams = await this.auth.getQueryParams({});
request.data = request.data ?? {};
// JSON as default
log(`Adding parameters to body`);
request.data = {
...request.data,
...authParams,
};
return request;
}
/**
* Sends a DELETE request to the specified URL.
*
* @param {string} url - The URL endpoint for the DELETE request.
* @return {Promise<VetchResponse<T>>} - The response from the DELETE request.
*/
async sendDeleteRequest<T>(url: string): Promise<VetchResponse<T>> {
const request = {
url,
method: HTTPMethods.DELETE,
} as VetchOptions;
return await this.sendRequest<T>(request);
}
/**
* Sends a POST request with form data to the specified URL.
*
* @param {string} url - The URL endpoint for the POST request.
* @param {Record<string, string>} [payload] - Optional payload containing form data to send with the POST request.
* @return {Promise<VetchResponse<T>>} - The response from the POST request.
*/
async sendFormSubmitRequest<T>(
url: string,
payload?: Record<string, string>,
): Promise<VetchResponse<T>> {
const request = {
url,
method: HTTPMethods.POST,
type: ContentType.FORM_URLENCODED,
headers: { Accept: 'application/json' },
...(payload ? { data: payload } : {}),
} as VetchOptions;
return await this.sendRequest<T>(request);
}
/**
* Sends a GET request to the specified URL with optional query parameters.
*
* @param {string} url - The URL endpoint for the GET request.
* @param {Record<string, unknown>} [queryParams] - Optional query parameters to append to the URL. These should be compatible with Node's URLSearchParams.
* @return {Promise<VetchResponse<T>>} - The response from the GET request.
*/
async sendGetRequest<T>(
url: string,
queryParams?: { [key: string]: unknown },
): Promise<VetchResponse<T>> {
const request = {
url,
method: HTTPMethods.GET,
...(queryParams ? { params: queryParams } : {}),
} as VetchOptions;
return await this.sendRequest<T>(request);
}
/**
* Sends a PATCH request to the specified URL with an optional payload.
*
* @param {string} url - The URL endpoint for the PATCH request.
* @param {Record<string, unknown>} [payload] - Optional payload to be sent as the body of the PATCH request.
* @return {Promise<VetchResponse<T>>} - The response from the PATCH request.
*/
async sendPatchRequest<T>(
url: string,
payload?: { [key: string]: unknown },
): Promise<VetchResponse<T>> {
return this.sendRequestWithData(HTTPMethods.PATCH, url, payload);
}
/**
* Sends a POST request to the specified URL with an optional payload.
*
* @param {string} url - The URL endpoint for the POST request.
* @param {Record<string, unknown>} [payload] - Optional payload to be sent as the body of the POST request.
* @return {Promise<VetchResponse<T>>} - The response from the POST request.
*/
async sendPostRequest<T>(
url: string,
payload?: { [key: string]: unknown },
): Promise<VetchResponse<T>> {
return this.sendRequestWithData(HTTPMethods.POST, url, payload);
}
/**
* Sends a PUT request to the specified URL with an optional payload.
*
* @param {string} url - The URL endpoint for the PUT request.
* @param {Record<string, unknown>} [payload] - Optional payload to be sent as the body of the PUT request.
* @return {Promise<VetchResponse<T>>} - The response from the PUT request.
*/
sendPutRequest<T>(
url: string,
payload?: { [key: string]: unknown },
): Promise<VetchResponse<T>> {
return this.sendRequestWithData(HTTPMethods.PUT, url, payload);
}
/**
* Sends a request with JSON-encoded data to the specified URL using the provided HTTP method.
*
* @param {HTTPMethods.POST | HTTPMethods.PATCH | HTTPMethods.PUT} method - The HTTP method to be used for the request (only POST, PATCH, or PUT are acceptable).
* @param {string} url - The URL endpoint for the request.
* @param {Record<string, unknown>} [payload] - Optional payload to be sent as the body of the request, JSON-encoded.
* @return {Promise<VetchResponse<T>>} - The response from the request.
*/
async sendRequestWithData<T>(
method: HTTPMethods.POST | HTTPMethods.PATCH | HTTPMethods.PUT,
url: string,
payload?: { [key: string]: unknown },
): Promise<VetchResponse<T>> {
const request = {
url,
method: method,
type: ContentType.JSON,
...(payload ? { data: payload } : {}),
} as VetchOptions;
return await this.sendRequest<T>(request);
}
/**
* Sends a request adding necessary headers, handling authentication, and parsing the response.
*
* @param {VetchOptions} request - The options defining the request, including URL, method, headers, and data.
* @return {Promise<VetchResponse<T>>} - The parsed response from the request.
*/
async sendRequest<T>(request: VetchOptions): Promise<VetchResponse<T>> {
const timeout = request.timeout || this.config.timeout;
const controller = new AbortController();
const timeoutId: NodeJS.Timeout = setTimeout(() => {
controller.abort();
}, timeout);
try {
log('Preparing request', request);
request = await this.prepareRequest(request);
const fetcRequest = {
url: request.url,
method: request.method,
headers: request.headers as Record<string, string>,
body: this.prepareBody(request),
...(timeout ? { signal: controller.signal } : {}),
};
log('Sending request', fetcRequest);
return await this.parseResponse(
request,
await fetch(request.url, fetcRequest),
);
} catch (error) {
if (error instanceof AbortError) {
log(`Request timed out after ${timeout}`);
}
throw error;
} finally {
clearTimeout(timeoutId);
}
}
/**
* Prepares the request with necessary headers, authentication, and query parameters.
*
* @param {VetchOptions} request - The initial request options.
* @return {Promise<VetchOptions>} - The modified request options.
*/
protected async prepareRequest(request: VetchOptions): Promise<VetchOptions> {
request.headers = {
...request.headers,
'user-agent': [
`@vonage/server-sdk/3.0.0`,
` node/${process.version.replace('v', '')}`,
this.config.appendUserAgent ? ` ${this.config.appendUserAgent}` : '',
].join(),
};
switch (request.type) {
case ContentType.FORM_URLENCODED:
request.headers['content-type'] = ContentType.FORM_URLENCODED;
break;
case ContentType.JSON:
request.headers['content-type'] = ContentType.JSON;
break;
}
request = await this.addAuthenticationToRequest(request);
const url = new URL(request.url as string);
const params = new URLSearchParams(request.params);
// copy params into the URL
for (const [param, value] of params.entries()) {
url.searchParams.append(param, value);
}
request.url = url.toString();
return request;
}
/**
* Prepares the body for the request based on the content type.
*
* @param {VetchOptions} request - The request options.
* @return {string | undefined} - The prepared request body as a string or undefined.
*/
protected prepareBody(request: VetchOptions): string | undefined {
request.headers = {
...request?.headers,
};
if (!request.data) {
return;
}
if (request.type === ContentType.JSON) {
return JSON.stringify(request.data);
}
if (request.type === ContentType.FORM_URLENCODED) {
const requestParams = new URLSearchParams(request.data);
requestParams.sort();
return requestParams.toString();
}
return undefined;
}
/**
* Parses the response based on its content type.
*
* @template T - The expected type of the parsed response data.
*
* @param {VetchOptions} request - The request options.
* @param {Response} response - The raw response from the request.
* @return {Promise<VetchResponse<T>>} - The parsed response.
*/
protected async parseResponse<T>(
request: VetchOptions,
response: Response,
): Promise<VetchResponse<T>> {
let decoded = null;
if (!response.ok) {
log('Request failed', response);
throw new VetchError(
`Request failed with status code ${response.status}`,
request,
response,
);
}
log('Request succeeded');
// eslint-disable-next-line max-len
const [contentType] = (response.headers.get('content-type') || '').split(
';',
);
log(`Response content type: ${contentType}`);
switch (contentType) {
case ContentType.FORM_URLENCODED:
log('Decoding form data');
decoded = response.body
? new URLSearchParams(await response.text())
: '';
break;
case ContentType.JSON:
log('Decoding JSON');
decoded = await response.json();
break;
default:
log('Decoding text');
decoded = await response.text();
}
log('Decoded body', decoded);
const responseHeaders = {};
for (const [header, value] of response.headers.entries()) {
Object.assign(response, header, value);
}
const result = {
data: decoded as T,
config: request,
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
request: request,
} as VetchResponse<T>;
log('Response', JSON.stringify(result, null, 2));
return result;
}
}