-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathRestClient.ts
417 lines (369 loc) · 12.1 KB
/
RestClient.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
416
417
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
ConsoleLogger as Logger,
Credentials,
DateUtils,
Signer,
} from '@aws-amplify/core';
import { apiOptions, ApiInfo } from './types';
import axios, { CancelTokenSource } from 'axios';
import { parse, format } from 'url';
const logger = new Logger('RestClient');
/**
* HTTP Client for REST requests. Send and receive JSON data.
* Sign request with AWS credentials if available
* Usage:
<pre>
const restClient = new RestClient();
restClient.get('...')
.then(function(data) {
console.log(data);
})
.catch(err => console.log(err));
</pre>
*/
export class RestClient {
private _options;
private _region: string = 'us-east-1'; // this will be updated by endpoint function
private _service: string = 'execute-api'; // this can be updated by endpoint function
private _custom_header = undefined; // this can be updated by endpoint function
/**
* This weak map provides functionality to let clients cancel
* in-flight axios requests. https://github.com/axios/axios#cancellation
*
* 1. For every axios request, a unique cancel token is generated and added in the request.
* 2. Promise for fulfilling the request is then mapped to that unique cancel token.
* 3. The promise is returned to the client.
* 4. Clients can either wait for the promise to fulfill or call `API.cancel(promise)` to cancel the request.
* 5. If `API.cancel(promise)` is called, then the corresponding cancel token is retrieved from the map below.
* 6. Promise returned to the client will be in rejected state with the error provided during cancel.
* 7. Clients can check if the error is because of cancelling by calling `API.isCancel(error)`.
*
* For more details, see https://github.com/aws-amplify/amplify-js/pull/3769#issuecomment-552660025
*/
private _cancelTokenMap: WeakMap<any, CancelTokenSource> = null;
Credentials = Credentials;
/**
* @param {RestClientOptions} [options] - Instance options
*/
constructor(options: apiOptions) {
this._options = options;
logger.debug('API Options', this._options);
if (this._cancelTokenMap == null) {
this._cancelTokenMap = new WeakMap();
}
}
/**
* Update AWS credentials
* @param {AWSCredentials} credentials - AWS credentials
*
updateCredentials(credentials: AWSCredentials) {
this.options.credentials = credentials;
}
*/
/**
* Basic HTTP request. Customizable
* @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
* @param {string} method - Request HTTP method
* @param {json} [init] - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
async ajax(urlOrApiInfo: string | ApiInfo, method: string, init) {
logger.debug(method, urlOrApiInfo);
let parsed_url;
let url: string;
let region: string = 'us-east-1';
let service: string = 'execute-api';
let custom_header: () => {
[key: string]: string;
} = undefined;
if (typeof urlOrApiInfo === 'string') {
parsed_url = this._parseUrl(urlOrApiInfo);
url = urlOrApiInfo;
} else {
({ endpoint: url, custom_header, region, service } = urlOrApiInfo);
parsed_url = this._parseUrl(urlOrApiInfo.endpoint);
}
const params = {
method,
url,
host: parsed_url.host,
path: parsed_url.path,
headers: {},
data: null,
responseType: 'json',
timeout: 0,
cancelToken: null,
};
const libraryHeaders = {};
const initParams = Object.assign({}, init);
const isAllResponse = initParams.response;
if (initParams.body) {
if (
typeof FormData === 'function' &&
initParams.body instanceof FormData
) {
libraryHeaders['Content-Type'] = 'multipart/form-data';
params.data = initParams.body;
} else {
libraryHeaders['Content-Type'] = 'application/json; charset=UTF-8';
params.data = JSON.stringify(initParams.body);
}
}
if (initParams.responseType) {
params.responseType = initParams.responseType;
}
if (initParams.withCredentials) {
params['withCredentials'] = initParams.withCredentials;
}
if (initParams.timeout) {
params.timeout = initParams.timeout;
}
if (initParams.cancellableToken) {
params.cancelToken = initParams.cancellableToken.token;
}
params['signerServiceInfo'] = initParams.signerServiceInfo;
// custom_header callback
const custom_header_obj =
typeof custom_header === 'function' ? await custom_header() : undefined;
params.headers = {
...libraryHeaders,
...custom_header_obj,
...initParams.headers,
};
// Intentionally discarding search
const { search, ...parsedUrl } = parse(url, true, true);
params.url = format({
...parsedUrl,
query: {
...parsedUrl.query,
...(initParams.queryStringParameters || {}),
},
});
// Do not sign the request if client has added 'Authorization' header,
// which means custom authorizer.
if (typeof params.headers['Authorization'] !== 'undefined') {
params.headers = Object.keys(params.headers).reduce((acc, k) => {
if (params.headers[k]) {
acc[k] = params.headers[k];
}
return acc;
// tslint:disable-next-line:align
}, {});
return this._request(params, isAllResponse);
}
let credentials;
try {
credentials = await this.Credentials.get();
} catch (error) {
logger.debug('No credentials available, the request will be unsigned');
return this._request(params, isAllResponse);
}
let signedParams;
try {
signedParams = this._sign({ ...params }, credentials, {
region,
service,
});
const response = await axios(signedParams);
return isAllResponse ? response : response.data;
} catch (error) {
logger.debug(error);
if (DateUtils.isClockSkewError(error)) {
const { headers } = error.response;
const dateHeader = headers && (headers.date || headers.Date);
const responseDate = new Date(dateHeader);
const requestDate = DateUtils.getDateFromHeaderString(
signedParams.headers['x-amz-date']
);
// Compare local clock to the server clock
if (DateUtils.isClockSkewed(responseDate)) {
const rawClientDate =
requestDate.getTime() - DateUtils.getClockOffset();
DateUtils.setClockOffset(responseDate.getTime() - rawClientDate);
return this.ajax(urlOrApiInfo, method, init);
}
}
throw error;
}
}
/**
* GET HTTP request
* @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
* @param {JSON} init - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
get(urlOrApiInfo: string | ApiInfo, init) {
return this.ajax(urlOrApiInfo, 'GET', init);
}
/**
* PUT HTTP request
* @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
* @param {json} init - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
put(urlOrApiInfo: string | ApiInfo, init) {
return this.ajax(urlOrApiInfo, 'PUT', init);
}
/**
* PATCH HTTP request
* @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
* @param {json} init - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
patch(urlOrApiInfo: string | ApiInfo, init) {
return this.ajax(urlOrApiInfo, 'PATCH', init);
}
/**
* POST HTTP request
* @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
* @param {json} init - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
post(urlOrApiInfo: string | ApiInfo, init) {
return this.ajax(urlOrApiInfo, 'POST', init);
}
/**
* DELETE HTTP request
* @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
* @param {json} init - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
del(urlOrApiInfo: string | ApiInfo, init) {
return this.ajax(urlOrApiInfo, 'DELETE', init);
}
/**
* HEAD HTTP request
* @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
* @param {json} init - Request extra params
* @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
*/
head(urlOrApiInfo: string | ApiInfo, init) {
return this.ajax(urlOrApiInfo, 'HEAD', init);
}
/**
* Cancel an inflight API request
* @param {Promise<any>} request - The request promise to cancel
* @param {string} [message] - A message to include in the cancelation exception
*/
cancel(request: Promise<any>, message?: string) {
const source = this._cancelTokenMap.get(request);
if (source) {
source.cancel(message);
return true;
}
return false;
}
/**
* Check if the request has a corresponding cancel token in the WeakMap.
* @params request - The request promise
* @return if the request has a corresponding cancel token.
*/
hasCancelToken(request: Promise<any>) {
return this._cancelTokenMap.has(request);
}
/**
* Checks to see if an error thrown is from an api request cancellation
* @param {any} error - Any error
* @return {boolean} - A boolean indicating if the error was from an api request cancellation
*/
isCancel(error): boolean {
return axios.isCancel(error);
}
/**
* Retrieves a new and unique cancel token which can be
* provided in an axios request to be cancelled later.
*/
getCancellableToken(): CancelTokenSource {
return axios.CancelToken.source();
}
/**
* Updates the weakmap with a response promise and its
* cancel token such that the cancel token can be easily
* retrieved (and used for cancelling the request)
*/
updateRequestToBeCancellable(
promise: Promise<any>,
cancelTokenSource: CancelTokenSource
) {
this._cancelTokenMap.set(promise, cancelTokenSource);
}
/**
* Getting endpoint for API
* @param {string} apiName - The name of the api
* @return {string} - The endpoint of the api
*/
endpoint(apiName: string) {
const cloud_logic_array = this._options.endpoints;
let response = '';
if (!Array.isArray(cloud_logic_array)) {
return response;
}
cloud_logic_array.forEach(v => {
if (v.name === apiName) {
response = v.endpoint;
if (typeof v.region === 'string') {
this._region = v.region;
} else if (typeof this._options.region === 'string') {
this._region = this._options.region;
}
if (typeof v.service === 'string') {
this._service = v.service || 'execute-api';
} else {
this._service = 'execute-api';
}
if (typeof v.custom_header === 'function') {
this._custom_header = v.custom_header;
} else {
this._custom_header = undefined;
}
}
});
return response;
}
/** private methods **/
private _sign(params, credentials, { service, region }) {
const { signerServiceInfo: signerServiceInfoParams, ...otherParams } =
params;
const endpoint_region: string =
region || this._region || this._options.region;
const endpoint_service: string =
service || this._service || this._options.service;
const creds = {
secret_key: credentials.secretAccessKey,
access_key: credentials.accessKeyId,
session_token: credentials.sessionToken,
};
const endpointInfo = {
region: endpoint_region,
service: endpoint_service,
};
const signerServiceInfo = Object.assign(
endpointInfo,
signerServiceInfoParams
);
const signed_params = Signer.sign(otherParams, creds, signerServiceInfo);
if (signed_params.data) {
signed_params.body = signed_params.data;
}
logger.debug('Signed Request: ', signed_params);
delete signed_params.headers['host'];
return signed_params;
}
private _request(params, isAllResponse = false) {
return axios(params)
.then(response => (isAllResponse ? response : response.data))
.catch(error => {
logger.debug(error);
throw error;
});
}
private _parseUrl(url) {
const parts = url.split('/');
return {
host: parts[2],
path: '/' + parts.slice(3).join('/'),
};
}
}