@aws-amplify/api-rest 3.5.6-unstable.7762f1a.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +3 -0
  2. package/internals/package.json +8 -0
  3. package/internals/server/package.json +8 -0
  4. package/lib/apis/common/handler.d.ts +27 -0
  5. package/lib/apis/common/handler.js +73 -0
  6. package/lib/apis/common/internalPost.d.ts +16 -0
  7. package/lib/apis/common/internalPost.js +65 -0
  8. package/lib/apis/common/publicApis.d.ts +8 -0
  9. package/lib/apis/common/publicApis.js +44 -0
  10. package/lib/apis/index.d.ts +203 -0
  11. package/lib/apis/index.js +215 -0
  12. package/lib/apis/server.d.ts +151 -0
  13. package/lib/apis/server.js +162 -0
  14. package/lib/errors/CanceledError.d.ts +17 -0
  15. package/lib/errors/CanceledError.js +32 -0
  16. package/lib/errors/RestApiError.d.ts +4 -0
  17. package/lib/errors/RestApiError.js +15 -0
  18. package/lib/errors/assertValidatonError.d.ts +5 -0
  19. package/lib/errors/assertValidatonError.js +17 -0
  20. package/lib/errors/index.d.ts +4 -0
  21. package/lib/errors/index.js +15 -0
  22. package/lib/errors/validation.d.ts +6 -0
  23. package/lib/errors/validation.js +19 -0
  24. package/lib/index.d.ts +2 -2
  25. package/lib/index.js +10 -6
  26. package/lib/internals/index.d.ts +19 -0
  27. package/lib/internals/index.js +30 -0
  28. package/lib/internals/server.d.ts +20 -0
  29. package/lib/internals/server.js +30 -0
  30. package/lib/server.d.ts +2 -0
  31. package/lib/server.js +14 -0
  32. package/lib/tsconfig.tsbuildinfo +1 -0
  33. package/lib/types/index.d.ts +90 -37
  34. package/lib/types/index.js +0 -23
  35. package/lib/utils/constants.d.ts +8 -0
  36. package/lib/utils/constants.js +13 -0
  37. package/lib/utils/createCancellableOperation.d.ts +12 -0
  38. package/lib/utils/createCancellableOperation.js +63 -0
  39. package/lib/utils/index.d.ts +6 -0
  40. package/lib/utils/index.js +17 -0
  41. package/lib/utils/logger.d.ts +2 -0
  42. package/lib/utils/logger.js +7 -0
  43. package/lib/utils/normalizeHeaders.d.ts +1 -0
  44. package/lib/utils/normalizeHeaders.js +13 -0
  45. package/lib/utils/parseSigningInfo.d.ts +14 -0
  46. package/lib/utils/parseSigningInfo.js +41 -0
  47. package/lib/utils/resolveApiUrl.d.ts +12 -0
  48. package/lib/utils/resolveApiUrl.js +40 -0
  49. package/lib/utils/resolveCredentials.d.ts +5 -0
  50. package/lib/utils/resolveCredentials.js +15 -0
  51. package/lib/utils/serviceError.d.ts +10 -0
  52. package/lib/utils/serviceError.js +30 -0
  53. package/lib-esm/apis/common/handler.d.ts +27 -0
  54. package/lib-esm/apis/common/handler.js +69 -0
  55. package/lib-esm/apis/common/internalPost.d.ts +16 -0
  56. package/lib-esm/apis/common/internalPost.js +59 -0
  57. package/lib-esm/apis/common/publicApis.d.ts +8 -0
  58. package/lib-esm/apis/common/publicApis.js +35 -0
  59. package/lib-esm/apis/index.d.ts +203 -0
  60. package/lib-esm/apis/index.js +206 -0
  61. package/lib-esm/apis/server.d.ts +151 -0
  62. package/lib-esm/apis/server.js +153 -0
  63. package/lib-esm/errors/CanceledError.d.ts +17 -0
  64. package/lib-esm/errors/CanceledError.js +27 -0
  65. package/lib-esm/errors/RestApiError.d.ts +4 -0
  66. package/lib-esm/errors/RestApiError.js +11 -0
  67. package/lib-esm/errors/assertValidatonError.d.ts +5 -0
  68. package/lib-esm/errors/assertValidatonError.js +13 -0
  69. package/lib-esm/errors/index.d.ts +4 -0
  70. package/lib-esm/errors/index.js +6 -0
  71. package/lib-esm/errors/validation.d.ts +6 -0
  72. package/lib-esm/errors/validation.js +16 -0
  73. package/lib-esm/index.d.ts +2 -2
  74. package/lib-esm/index.js +2 -3
  75. package/lib-esm/internals/index.d.ts +19 -0
  76. package/lib-esm/internals/index.js +24 -0
  77. package/lib-esm/internals/server.d.ts +20 -0
  78. package/lib-esm/internals/server.js +24 -0
  79. package/lib-esm/server.d.ts +2 -0
  80. package/lib-esm/server.js +4 -0
  81. package/lib-esm/tsconfig.tsbuildinfo +1 -0
  82. package/lib-esm/types/index.d.ts +90 -37
  83. package/lib-esm/types/index.js +1 -23
  84. package/lib-esm/utils/constants.d.ts +8 -0
  85. package/lib-esm/utils/constants.js +10 -0
  86. package/lib-esm/utils/createCancellableOperation.d.ts +12 -0
  87. package/lib-esm/utils/createCancellableOperation.js +59 -0
  88. package/lib-esm/utils/index.d.ts +6 -0
  89. package/lib-esm/utils/index.js +8 -0
  90. package/lib-esm/utils/logger.d.ts +2 -0
  91. package/lib-esm/utils/logger.js +4 -0
  92. package/lib-esm/utils/normalizeHeaders.d.ts +1 -0
  93. package/lib-esm/utils/normalizeHeaders.js +9 -0
  94. package/lib-esm/utils/parseSigningInfo.d.ts +14 -0
  95. package/lib-esm/utils/parseSigningInfo.js +37 -0
  96. package/lib-esm/utils/resolveApiUrl.d.ts +12 -0
  97. package/lib-esm/utils/resolveApiUrl.js +36 -0
  98. package/lib-esm/utils/resolveCredentials.d.ts +5 -0
  99. package/lib-esm/utils/resolveCredentials.js +11 -0
  100. package/lib-esm/utils/serviceError.d.ts +10 -0
  101. package/lib-esm/utils/serviceError.js +25 -0
  102. package/package.json +113 -105
  103. package/server/package.json +8 -0
  104. package/src/apis/common/handler.ts +109 -0
  105. package/src/apis/common/internalPost.ts +81 -0
  106. package/src/apis/common/publicApis.ts +99 -0
  107. package/src/apis/index.ts +239 -0
  108. package/src/apis/server.ts +209 -0
  109. package/src/errors/CanceledError.ts +33 -0
  110. package/src/errors/RestApiError.ts +17 -0
  111. package/src/errors/assertValidatonError.ts +19 -0
  112. package/src/errors/index.ts +7 -0
  113. package/src/errors/validation.ts +20 -0
  114. package/src/index.ts +2 -2
  115. package/src/internals/index.ts +31 -0
  116. package/src/internals/server.ts +37 -0
  117. package/src/server.ts +5 -0
  118. package/src/types/index.ts +95 -44
  119. package/src/utils/constants.ts +15 -0
  120. package/src/utils/createCancellableOperation.ts +94 -0
  121. package/src/utils/index.ts +9 -0
  122. package/src/utils/logger.ts +6 -0
  123. package/src/utils/normalizeHeaders.ts +10 -0
  124. package/src/utils/parseSigningInfo.ts +52 -0
  125. package/src/utils/resolveApiUrl.ts +51 -0
  126. package/src/utils/resolveCredentials.ts +17 -0
  127. package/src/utils/serviceError.ts +35 -0
  128. package/lib/.tsbuildinfo +0 -3
  129. package/lib/RestAPI.d.ts +0 -108
  130. package/lib/RestAPI.js +0 -282
  131. package/lib/RestAPI.js.map +0 -1
  132. package/lib/RestClient.d.ts +0 -138
  133. package/lib/RestClient.js +0 -368
  134. package/lib/RestClient.js.map +0 -1
  135. package/lib/index.js.map +0 -1
  136. package/lib/types/index.js.map +0 -1
  137. package/lib-esm/.tsbuildinfo +0 -3
  138. package/lib-esm/RestAPI.d.ts +0 -108
  139. package/lib-esm/RestAPI.js +0 -280
  140. package/lib-esm/RestAPI.js.map +0 -1
  141. package/lib-esm/RestClient.d.ts +0 -138
  142. package/lib-esm/RestClient.js +0 -366
  143. package/lib-esm/RestClient.js.map +0 -1
  144. package/lib-esm/index.js.map +0 -1
  145. package/lib-esm/types/index.js.map +0 -1
  146. package/src/RestAPI.ts +0 -338
  147. package/src/RestClient.ts +0 -417
package/src/RestClient.ts DELETED
@@ -1,417 +0,0 @@
1
- // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import {
5
- ConsoleLogger as Logger,
6
- Credentials,
7
- DateUtils,
8
- Signer,
9
- } from '@aws-amplify/core';
10
-
11
- import { apiOptions, ApiInfo } from './types';
12
- import axios, { CancelTokenSource } from 'axios';
13
- import { parse, format } from 'url';
14
-
15
- const logger = new Logger('RestClient');
16
-
17
- /**
18
- * HTTP Client for REST requests. Send and receive JSON data.
19
- * Sign request with AWS credentials if available
20
- * Usage:
21
- <pre>
22
- const restClient = new RestClient();
23
- restClient.get('...')
24
- .then(function(data) {
25
- console.log(data);
26
- })
27
- .catch(err => console.log(err));
28
- </pre>
29
- */
30
- export class RestClient {
31
- private _options;
32
- private _region: string = 'us-east-1'; // this will be updated by endpoint function
33
- private _service: string = 'execute-api'; // this can be updated by endpoint function
34
- private _custom_header = undefined; // this can be updated by endpoint function
35
-
36
- /**
37
- * This weak map provides functionality to let clients cancel
38
- * in-flight axios requests. https://github.com/axios/axios#cancellation
39
- *
40
- * 1. For every axios request, a unique cancel token is generated and added in the request.
41
- * 2. Promise for fulfilling the request is then mapped to that unique cancel token.
42
- * 3. The promise is returned to the client.
43
- * 4. Clients can either wait for the promise to fulfill or call `API.cancel(promise)` to cancel the request.
44
- * 5. If `API.cancel(promise)` is called, then the corresponding cancel token is retrieved from the map below.
45
- * 6. Promise returned to the client will be in rejected state with the error provided during cancel.
46
- * 7. Clients can check if the error is because of cancelling by calling `API.isCancel(error)`.
47
- *
48
- * For more details, see https://github.com/aws-amplify/amplify-js/pull/3769#issuecomment-552660025
49
- */
50
- private _cancelTokenMap: WeakMap<any, CancelTokenSource> = null;
51
-
52
- Credentials = Credentials;
53
-
54
- /**
55
- * @param {RestClientOptions} [options] - Instance options
56
- */
57
- constructor(options: apiOptions) {
58
- this._options = options;
59
- logger.debug('API Options', this._options);
60
- if (this._cancelTokenMap == null) {
61
- this._cancelTokenMap = new WeakMap();
62
- }
63
- }
64
-
65
- /**
66
- * Update AWS credentials
67
- * @param {AWSCredentials} credentials - AWS credentials
68
- *
69
- updateCredentials(credentials: AWSCredentials) {
70
- this.options.credentials = credentials;
71
- }
72
- */
73
- /**
74
- * Basic HTTP request. Customizable
75
- * @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
76
- * @param {string} method - Request HTTP method
77
- * @param {json} [init] - Request extra params
78
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
79
- */
80
- async ajax(urlOrApiInfo: string | ApiInfo, method: string, init) {
81
- logger.debug(method, urlOrApiInfo);
82
-
83
- let parsed_url;
84
- let url: string;
85
- let region: string = 'us-east-1';
86
- let service: string = 'execute-api';
87
- let custom_header: () => {
88
- [key: string]: string;
89
- } = undefined;
90
-
91
- if (typeof urlOrApiInfo === 'string') {
92
- parsed_url = this._parseUrl(urlOrApiInfo);
93
- url = urlOrApiInfo;
94
- } else {
95
- ({ endpoint: url, custom_header, region, service } = urlOrApiInfo);
96
- parsed_url = this._parseUrl(urlOrApiInfo.endpoint);
97
- }
98
-
99
- const params = {
100
- method,
101
- url,
102
- host: parsed_url.host,
103
- path: parsed_url.path,
104
- headers: {},
105
- data: null,
106
- responseType: 'json',
107
- timeout: 0,
108
- cancelToken: null,
109
- };
110
-
111
- const libraryHeaders = {};
112
- const initParams = Object.assign({}, init);
113
- const isAllResponse = initParams.response;
114
- if (initParams.body) {
115
- if (
116
- typeof FormData === 'function' &&
117
- initParams.body instanceof FormData
118
- ) {
119
- libraryHeaders['Content-Type'] = 'multipart/form-data';
120
- params.data = initParams.body;
121
- } else {
122
- libraryHeaders['Content-Type'] = 'application/json; charset=UTF-8';
123
- params.data = JSON.stringify(initParams.body);
124
- }
125
- }
126
- if (initParams.responseType) {
127
- params.responseType = initParams.responseType;
128
- }
129
- if (initParams.withCredentials) {
130
- params['withCredentials'] = initParams.withCredentials;
131
- }
132
- if (initParams.timeout) {
133
- params.timeout = initParams.timeout;
134
- }
135
- if (initParams.cancellableToken) {
136
- params.cancelToken = initParams.cancellableToken.token;
137
- }
138
-
139
- params['signerServiceInfo'] = initParams.signerServiceInfo;
140
-
141
- // custom_header callback
142
- const custom_header_obj =
143
- typeof custom_header === 'function' ? await custom_header() : undefined;
144
-
145
- params.headers = {
146
- ...libraryHeaders,
147
- ...custom_header_obj,
148
- ...initParams.headers,
149
- };
150
-
151
- // Intentionally discarding search
152
- const { search, ...parsedUrl } = parse(url, true, true);
153
- params.url = format({
154
- ...parsedUrl,
155
- query: {
156
- ...parsedUrl.query,
157
- ...(initParams.queryStringParameters || {}),
158
- },
159
- });
160
-
161
- // Do not sign the request if client has added 'Authorization' header,
162
- // which means custom authorizer.
163
- if (typeof params.headers['Authorization'] !== 'undefined') {
164
- params.headers = Object.keys(params.headers).reduce((acc, k) => {
165
- if (params.headers[k]) {
166
- acc[k] = params.headers[k];
167
- }
168
- return acc;
169
- // tslint:disable-next-line:align
170
- }, {});
171
- return this._request(params, isAllResponse);
172
- }
173
-
174
- let credentials;
175
- try {
176
- credentials = await this.Credentials.get();
177
- } catch (error) {
178
- logger.debug('No credentials available, the request will be unsigned');
179
- return this._request(params, isAllResponse);
180
- }
181
- let signedParams;
182
- try {
183
- signedParams = this._sign({ ...params }, credentials, {
184
- region,
185
- service,
186
- });
187
- const response = await axios(signedParams);
188
- return isAllResponse ? response : response.data;
189
- } catch (error) {
190
- logger.debug(error);
191
- if (DateUtils.isClockSkewError(error)) {
192
- const { headers } = error.response;
193
- const dateHeader = headers && (headers.date || headers.Date);
194
- const responseDate = new Date(dateHeader);
195
- const requestDate = DateUtils.getDateFromHeaderString(
196
- signedParams.headers['x-amz-date']
197
- );
198
-
199
- // Compare local clock to the server clock
200
- if (DateUtils.isClockSkewed(responseDate)) {
201
- DateUtils.setClockOffset(
202
- responseDate.getTime() - requestDate.getTime()
203
- );
204
-
205
- return this.ajax(urlOrApiInfo, method, init);
206
- }
207
- }
208
- throw error;
209
- }
210
- }
211
-
212
- /**
213
- * GET HTTP request
214
- * @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
215
- * @param {JSON} init - Request extra params
216
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
217
- */
218
- get(urlOrApiInfo: string | ApiInfo, init) {
219
- return this.ajax(urlOrApiInfo, 'GET', init);
220
- }
221
-
222
- /**
223
- * PUT HTTP request
224
- * @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
225
- * @param {json} init - Request extra params
226
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
227
- */
228
- put(urlOrApiInfo: string | ApiInfo, init) {
229
- return this.ajax(urlOrApiInfo, 'PUT', init);
230
- }
231
-
232
- /**
233
- * PATCH HTTP request
234
- * @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
235
- * @param {json} init - Request extra params
236
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
237
- */
238
- patch(urlOrApiInfo: string | ApiInfo, init) {
239
- return this.ajax(urlOrApiInfo, 'PATCH', init);
240
- }
241
-
242
- /**
243
- * POST HTTP request
244
- * @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
245
- * @param {json} init - Request extra params
246
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
247
- */
248
- post(urlOrApiInfo: string | ApiInfo, init) {
249
- return this.ajax(urlOrApiInfo, 'POST', init);
250
- }
251
-
252
- /**
253
- * DELETE HTTP request
254
- * @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
255
- * @param {json} init - Request extra params
256
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
257
- */
258
- del(urlOrApiInfo: string | ApiInfo, init) {
259
- return this.ajax(urlOrApiInfo, 'DELETE', init);
260
- }
261
-
262
- /**
263
- * HEAD HTTP request
264
- * @param {string | ApiInfo } urlOrApiInfo - Full request URL or Api information
265
- * @param {json} init - Request extra params
266
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
267
- */
268
- head(urlOrApiInfo: string | ApiInfo, init) {
269
- return this.ajax(urlOrApiInfo, 'HEAD', init);
270
- }
271
-
272
- /**
273
- * Cancel an inflight API request
274
- * @param {Promise<any>} request - The request promise to cancel
275
- * @param {string} [message] - A message to include in the cancelation exception
276
- */
277
- cancel(request: Promise<any>, message?: string) {
278
- const source = this._cancelTokenMap.get(request);
279
- if (source) {
280
- source.cancel(message);
281
- return true;
282
- }
283
- return false;
284
- }
285
-
286
- /**
287
- * Check if the request has a corresponding cancel token in the WeakMap.
288
- * @params request - The request promise
289
- * @return if the request has a corresponding cancel token.
290
- */
291
- hasCancelToken(request: Promise<any>) {
292
- return this._cancelTokenMap.has(request);
293
- }
294
-
295
- /**
296
- * Checks to see if an error thrown is from an api request cancellation
297
- * @param {any} error - Any error
298
- * @return {boolean} - A boolean indicating if the error was from an api request cancellation
299
- */
300
- isCancel(error): boolean {
301
- return axios.isCancel(error);
302
- }
303
-
304
- /**
305
- * Retrieves a new and unique cancel token which can be
306
- * provided in an axios request to be cancelled later.
307
- */
308
- getCancellableToken(): CancelTokenSource {
309
- return axios.CancelToken.source();
310
- }
311
-
312
- /**
313
- * Updates the weakmap with a response promise and its
314
- * cancel token such that the cancel token can be easily
315
- * retrieved (and used for cancelling the request)
316
- */
317
- updateRequestToBeCancellable(
318
- promise: Promise<any>,
319
- cancelTokenSource: CancelTokenSource
320
- ) {
321
- this._cancelTokenMap.set(promise, cancelTokenSource);
322
- }
323
-
324
- /**
325
- * Getting endpoint for API
326
- * @param {string} apiName - The name of the api
327
- * @return {string} - The endpoint of the api
328
- */
329
- endpoint(apiName: string) {
330
- const cloud_logic_array = this._options.endpoints;
331
- let response = '';
332
-
333
- if (!Array.isArray(cloud_logic_array)) {
334
- return response;
335
- }
336
-
337
- cloud_logic_array.forEach(v => {
338
- if (v.name === apiName) {
339
- response = v.endpoint;
340
- if (typeof v.region === 'string') {
341
- this._region = v.region;
342
- } else if (typeof this._options.region === 'string') {
343
- this._region = this._options.region;
344
- }
345
- if (typeof v.service === 'string') {
346
- this._service = v.service || 'execute-api';
347
- } else {
348
- this._service = 'execute-api';
349
- }
350
- if (typeof v.custom_header === 'function') {
351
- this._custom_header = v.custom_header;
352
- } else {
353
- this._custom_header = undefined;
354
- }
355
- }
356
- });
357
- return response;
358
- }
359
-
360
- /** private methods **/
361
-
362
- private _sign(params, credentials, { service, region }) {
363
- const { signerServiceInfo: signerServiceInfoParams, ...otherParams } =
364
- params;
365
-
366
- const endpoint_region: string =
367
- region || this._region || this._options.region;
368
- const endpoint_service: string =
369
- service || this._service || this._options.service;
370
-
371
- const creds = {
372
- secret_key: credentials.secretAccessKey,
373
- access_key: credentials.accessKeyId,
374
- session_token: credentials.sessionToken,
375
- };
376
-
377
- const endpointInfo = {
378
- region: endpoint_region,
379
- service: endpoint_service,
380
- };
381
-
382
- const signerServiceInfo = Object.assign(
383
- endpointInfo,
384
- signerServiceInfoParams
385
- );
386
-
387
- const signed_params = Signer.sign(otherParams, creds, signerServiceInfo);
388
-
389
- if (signed_params.data) {
390
- signed_params.body = signed_params.data;
391
- }
392
-
393
- logger.debug('Signed Request: ', signed_params);
394
-
395
- delete signed_params.headers['host'];
396
-
397
- return signed_params;
398
- }
399
-
400
- private _request(params, isAllResponse = false) {
401
- return axios(params)
402
- .then(response => (isAllResponse ? response : response.data))
403
- .catch(error => {
404
- logger.debug(error);
405
- throw error;
406
- });
407
- }
408
-
409
- private _parseUrl(url) {
410
- const parts = url.split('/');
411
-
412
- return {
413
- host: parts[2],
414
- path: '/' + parts.slice(3).join('/'),
415
- };
416
- }
417
- }