@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
@@ -0,0 +1,37 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import {
4
+ AmplifyServer,
5
+ getAmplifyServerContext,
6
+ } from '@aws-amplify/core/internals/adapter-core';
7
+
8
+ import { post as internalPost } from '../apis/common/internalPost';
9
+ import { InternalPostInput } from '../types';
10
+
11
+ /**
12
+ * Internal-only REST POST handler to send GraphQL request to given endpoint. By default, it will use IAM to authorize
13
+ * the request. In some auth modes, the IAM auth has to be disabled. Here's how to set up the request auth correctly:
14
+ * * If auth mode is 'iam', you MUST NOT set 'authorization' header and 'x-api-key' header, since it would disable IAM
15
+ * auth. You MUST also set 'input.options.signingServiceInfo' option.
16
+ * * The including 'input.options.signingServiceInfo.service' and 'input.options.signingServiceInfo.region' are
17
+ * optional. If omitted, the signing service and region will be inferred from url.
18
+ * * If auth mode is 'none', you MUST NOT set 'options.signingServiceInfo' option.
19
+ * * If auth mode is 'apiKey', you MUST set 'x-api-key' custom header.
20
+ * * If auth mode is 'oidc' or 'lambda' or 'userPool', you MUST set 'authorization' header.
21
+ *
22
+ * To make the internal post cancellable, you must also call `updateRequestToBeCancellable()` with the promise from
23
+ * internal post call and the abort controller supplied to the internal post call.
24
+ *
25
+ * @internal
26
+ */
27
+ export const post = (
28
+ contextSpec: AmplifyServer.ContextSpec,
29
+ input: InternalPostInput
30
+ ) => {
31
+ return internalPost(getAmplifyServerContext(contextSpec).amplify, input);
32
+ };
33
+
34
+ export {
35
+ cancel,
36
+ updateRequestToBeCancellable,
37
+ } from '../apis/common/internalPost';
package/src/server.ts ADDED
@@ -0,0 +1,5 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export { isCancelError } from './errors/CanceledError';
5
+ export { get, post, put, del, head, patch } from './apis/server';
@@ -1,63 +1,114 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
+ import { DocumentType } from '@aws-amplify/core/internals/utils';
4
+
5
+ export type GetInput = ApiInput<RestApiOptionsBase>;
6
+ export type PostInput = ApiInput<RestApiOptionsBase>;
7
+ export type PutInput = ApiInput<RestApiOptionsBase>;
8
+ export type PatchInput = ApiInput<RestApiOptionsBase>;
9
+ export type DeleteInput = ApiInput<Omit<RestApiOptionsBase, 'body'>>;
10
+ export type HeadInput = ApiInput<Omit<RestApiOptionsBase, 'body'>>;
11
+
12
+ export type GetOperation = Operation<RestApiResponse>;
13
+ export type PostOperation = Operation<RestApiResponse>;
14
+ export type PutOperation = Operation<RestApiResponse>;
15
+ export type PatchOperation = Operation<RestApiResponse>;
16
+ export type DeleteOperation = Operation<Omit<RestApiResponse, 'body'>>;
17
+ export type HeadOperation = Operation<Omit<RestApiResponse, 'body'>>;
3
18
 
4
19
  /**
5
- * RestClient instance options
20
+ * @internal
6
21
  */
7
- export class RestClientOptions {
8
- /** AWS credentials */
9
- credentials: AWSCredentials;
10
-
22
+ export type RestApiOptionsBase = {
23
+ headers?: Headers;
24
+ queryParams?: Record<string, string>;
25
+ body?: DocumentType | FormData;
11
26
  /**
12
- * Lookup key of AWS credentials.
13
- * If credentials not provided then lookup from sessionStorage.
14
- * Default 'awsCredentials'
27
+ * Option controls whether or not cross-site Access-Control requests should be made using credentials
28
+ * such as cookies, authorization headers or TLS client certificates. It has no effect on same-origin requests.
29
+ * If set to `true`, the request will include credentials such as cookies, authorization headers, TLS
30
+ * client certificates, and so on. Moreover the response cookies will also be set.
31
+ * If set to `false`, the cross-site request will not include credentials, and the response cookies from a different
32
+ * domain will be ignored.
33
+ *
34
+ * @default false
35
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}
15
36
  */
16
- credentials_key: string;
37
+ withCredentials?: boolean;
38
+ };
39
+
40
+ type Headers = Record<string, string>;
41
+
42
+ /**
43
+ * Type representing an operation that can be canceled.
44
+ *
45
+ * @internal
46
+ */
47
+ export type Operation<Response> = {
48
+ response: Promise<Response>;
49
+ cancel: (abortMessage?: string) => void;
50
+ };
17
51
 
18
- /** Additional headers for all requests send by this client. e.g. user-agent */
19
- headers: object;
52
+ type ResponsePayload = {
53
+ blob: () => Promise<Blob>;
54
+ json: () => Promise<DocumentType>;
55
+ text: () => Promise<string>;
56
+ };
20
57
 
21
- constructor() {
22
- this.credentials_key = 'awsCredentials';
23
- this.headers = {};
24
- }
58
+ /**
59
+ * Basic response type of REST API.
60
+ *
61
+ * @internal
62
+ */
63
+ export interface RestApiResponse {
64
+ body: ResponsePayload;
65
+ statusCode: number;
66
+ headers: Headers;
25
67
  }
26
68
 
27
69
  /**
28
- * AWS credentials needed for RestClient
70
+ * @internal
29
71
  */
30
- export class AWSCredentials {
72
+ export type ApiInput<Options> = {
31
73
  /**
32
- * Secret Access Key
33
- *
34
- * [Access Key ID and Secret Access Key]
35
- * (http://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys)
74
+ * Name of the REST API configured in Amplify singleton.
36
75
  */
37
- secretAccessKey: string;
38
-
76
+ apiName: string;
39
77
  /**
40
- * Access Key ID
41
- *
42
- * [Access Key ID and Secret Access Key]
43
- * (http://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys)
78
+ * Path of the REST API.
44
79
  */
45
- accessKeyId: string;
46
-
47
- /** Access Token of current session */
48
- sessionToken: string;
49
- }
50
-
51
- // TODO: remove this once unauth creds are figured out
52
- export interface apiOptions {
53
- headers: object;
54
- endpoints: object;
55
- credentials?: object;
56
- }
80
+ path: string;
81
+ /**
82
+ * Options to overwrite the REST API call behavior.
83
+ */
84
+ options?: Options;
85
+ };
57
86
 
58
- export type ApiInfo = {
59
- endpoint: string;
60
- region?: string;
61
- service?: string;
62
- custom_header?: () => { [key: string]: string };
87
+ /**
88
+ * Input type to invoke REST POST API from GraphQl client.
89
+ * @internal
90
+ */
91
+ export type InternalPostInput = {
92
+ // Resolved GraphQl endpoint url
93
+ url: URL;
94
+ options?: RestApiOptionsBase & {
95
+ /**
96
+ * Internal-only option for GraphQL client to provide the IAM signing service and region.
97
+ * * If auth mode is 'iam', you MUST set this value.
98
+ * * If auth mode is 'none', you MUST NOT set this value;
99
+ * * If auth mode is 'apiKey' or 'oidc' or 'lambda' or 'userPool' because associated
100
+ * headers are provided, this value is ignored.
101
+ */
102
+ signingServiceInfo?: {
103
+ service?: string;
104
+ region?: string;
105
+ };
106
+ };
107
+ /**
108
+ * The abort controller to cancel the in-flight POST request.
109
+ * Required if you want to make the internal post request cancellable. To make the internal post cancellable, you
110
+ * must also call `updateRequestToBeCancellable()` with the promise from internal post call and the abort
111
+ * controller.
112
+ */
113
+ abortController?: AbortController;
63
114
  };
@@ -0,0 +1,15 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export const DEFAULT_REST_IAM_SIGNING_SERVICE = 'execute-api';
5
+
6
+ export const DEFAULT_APPSYNC_API_SERVICE = 'appsync-api';
7
+
8
+ export const DEFAULT_IAM_SIGNING_REGION = 'us-east-1';
9
+
10
+ /**
11
+ * The REST endpoints generated by API Gateway
12
+ * @see {@link https://docs.aws.amazon.com/general/latest/gr/apigateway.html#apigateway_region_data_plane}
13
+ */
14
+ export const APIG_HOSTNAME_PATTERN =
15
+ /^.+\.([a-z0-9-]+)\.([a-z0-9-]+)\.amazonaws\.com/;
@@ -0,0 +1,94 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { HttpResponse } from '@aws-amplify/core/internals/aws-client-utils';
5
+ import { CanceledError } from '../errors';
6
+ import { Operation } from '../types';
7
+ import { parseRestApiServiceError } from './serviceError';
8
+ import { logger } from './logger';
9
+
10
+ /**
11
+ * Create a cancellable operation conforming to the internal POST API interface.
12
+ * @internal
13
+ */
14
+ export function createCancellableOperation(
15
+ handler: () => Promise<HttpResponse>,
16
+ abortController: AbortController
17
+ ): Promise<HttpResponse>;
18
+
19
+ /**
20
+ * Create a cancellable operation conforming to the external REST API interface.
21
+ * @internal
22
+ */
23
+ export function createCancellableOperation(
24
+ handler: (signal: AbortSignal) => Promise<HttpResponse>
25
+ ): Operation<HttpResponse>;
26
+
27
+ /**
28
+ * @internal
29
+ */
30
+ export function createCancellableOperation(
31
+ handler:
32
+ | ((signal: AbortSignal) => Promise<HttpResponse>)
33
+ | (() => Promise<HttpResponse>),
34
+ abortController?: AbortController
35
+ ): Operation<HttpResponse> | Promise<HttpResponse> {
36
+ const isInternalPost = (
37
+ handler:
38
+ | ((signal: AbortSignal) => Promise<HttpResponse>)
39
+ | (() => Promise<HttpResponse>)
40
+ ): handler is () => Promise<HttpResponse> => !!abortController;
41
+
42
+ // For creating a cancellable operation for public REST APIs, we need to create an AbortController
43
+ // internally. Whereas for internal POST APIs, we need to accept in the AbortController from the
44
+ // callers.
45
+ const publicApisAbortController = new AbortController();
46
+ const publicApisAbortSignal = publicApisAbortController.signal;
47
+ const internalPostAbortSignal = abortController?.signal;
48
+
49
+ const job = async () => {
50
+ try {
51
+ const response = await (isInternalPost(handler)
52
+ ? handler()
53
+ : handler(publicApisAbortSignal));
54
+
55
+ if (response.statusCode >= 300) {
56
+ throw await parseRestApiServiceError(response)!;
57
+ }
58
+ return response;
59
+ } catch (error: any) {
60
+ const abortSignal = internalPostAbortSignal ?? publicApisAbortSignal;
61
+ if (error.name === 'AbortError' || abortSignal?.aborted === true) {
62
+ const canceledError = new CanceledError({
63
+ ...(abortSignal.reason ? { message: abortSignal.reason } : undefined),
64
+ underlyingError: error,
65
+ });
66
+ logger.debug(error);
67
+ throw canceledError;
68
+ }
69
+ logger.debug(error);
70
+ throw error;
71
+ }
72
+ };
73
+
74
+ if (isInternalPost(handler)) {
75
+ return job();
76
+ } else {
77
+ const cancel = (abortMessage?: string) => {
78
+ if (publicApisAbortSignal.aborted === true) {
79
+ return;
80
+ }
81
+ publicApisAbortController.abort(abortMessage);
82
+ // Abort reason is not widely support enough across runtimes and and browsers, so we set it
83
+ // if it is not already set.
84
+ if (abortMessage && publicApisAbortSignal.reason !== abortMessage) {
85
+ type AbortSignalWithReasonSupport = Omit<AbortSignal, 'reason'> & {
86
+ reason?: string;
87
+ };
88
+ (publicApisAbortSignal as AbortSignalWithReasonSupport)['reason'] =
89
+ abortMessage;
90
+ }
91
+ };
92
+ return { response: job(), cancel };
93
+ }
94
+ }
@@ -0,0 +1,9 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export { createCancellableOperation } from './createCancellableOperation';
5
+ export { resolveCredentials } from './resolveCredentials';
6
+ export { parseSigningInfo } from './parseSigningInfo';
7
+ export { parseRestApiServiceError } from './serviceError';
8
+ export { resolveApiUrl } from './resolveApiUrl';
9
+ export { logger } from './logger';
@@ -0,0 +1,6 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { ConsoleLogger } from '@aws-amplify/core';
5
+
6
+ export const logger = new ConsoleLogger('RestApis');
@@ -0,0 +1,10 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ export const normalizeHeaders = (headers?: Record<string, string>) => {
5
+ const normalizedHeaders: Record<string, string> = {};
6
+ for (const key in headers) {
7
+ normalizedHeaders[key.toLowerCase()] = headers[key];
8
+ }
9
+ return normalizedHeaders;
10
+ };
@@ -0,0 +1,52 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { AmplifyClassV6 } from '@aws-amplify/core';
5
+ import {
6
+ APIG_HOSTNAME_PATTERN,
7
+ DEFAULT_IAM_SIGNING_REGION,
8
+ DEFAULT_REST_IAM_SIGNING_SERVICE,
9
+ } from './constants';
10
+
11
+ /**
12
+ * Infer the signing service and region from the given URL, and for REST API only, from the Amplify configuration.
13
+ * It supports raw API Gateway endpoint and AppSync endpoint.
14
+ *
15
+ * @internal
16
+ */
17
+ export const parseSigningInfo = (
18
+ url: URL,
19
+ restApiOptions?: {
20
+ amplify: AmplifyClassV6;
21
+ apiName: string;
22
+ }
23
+ ) => {
24
+ const {
25
+ service: signingService = DEFAULT_REST_IAM_SIGNING_SERVICE,
26
+ region: signingRegion = DEFAULT_IAM_SIGNING_REGION,
27
+ } =
28
+ restApiOptions?.amplify.getConfig()?.API?.REST?.[restApiOptions?.apiName] ??
29
+ {};
30
+ const { hostname } = url;
31
+ const [, service, region] = APIG_HOSTNAME_PATTERN.exec(hostname) ?? [];
32
+ if (service === DEFAULT_REST_IAM_SIGNING_SERVICE) {
33
+ // The configured endpoint is an API Gateway endpoint
34
+ // @see: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-call-api.html
35
+ return {
36
+ service,
37
+ region: region ?? signingRegion,
38
+ };
39
+ } else if (service === 'appsync-api') {
40
+ // AppSync endpoint is internally supported because GraphQL operation will send request using POST handler.
41
+ // example: https://xxxx.appsync-api.us-east-1.amazonaws.com/graphql
42
+ return {
43
+ service: 'appsync',
44
+ region: region ?? signingRegion,
45
+ };
46
+ } else {
47
+ return {
48
+ service: signingService,
49
+ region: signingRegion,
50
+ };
51
+ }
52
+ };
@@ -0,0 +1,51 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { AmplifyClassV6 } from '@aws-amplify/core';
5
+ import {
6
+ AmplifyUrl,
7
+ AmplifyUrlSearchParams,
8
+ } from '@aws-amplify/core/internals/utils';
9
+ import {
10
+ RestApiError,
11
+ RestApiValidationErrorCode,
12
+ assertValidationError,
13
+ validationErrorMap,
14
+ } from '../errors';
15
+
16
+ /**
17
+ * Resolve the REST API request URL by:
18
+ * 1. Loading the REST API endpoint from the Amplify configuration with corresponding API name.
19
+ * 2. Appending the path to the endpoint.
20
+ * 3. Merge the query parameters from path and the queryParameter argument which is taken from the public REST API
21
+ * options.
22
+ * 4. Validating the resulting URL string.
23
+ *
24
+ * @internal
25
+ */
26
+ export const resolveApiUrl = (
27
+ amplify: AmplifyClassV6,
28
+ apiName: string,
29
+ path: string,
30
+ queryParams?: Record<string, string>
31
+ ): URL => {
32
+ const urlStr = amplify.getConfig()?.API?.REST?.[apiName]?.endpoint;
33
+ assertValidationError(!!urlStr, RestApiValidationErrorCode.InvalidApiName);
34
+ try {
35
+ const url = new AmplifyUrl(urlStr + path);
36
+ if (queryParams) {
37
+ const mergedQueryParams = new AmplifyUrlSearchParams(url.searchParams);
38
+ Object.entries(queryParams).forEach(([key, value]) => {
39
+ mergedQueryParams.set(key, value);
40
+ });
41
+ url.search = new AmplifyUrlSearchParams(mergedQueryParams).toString();
42
+ }
43
+ return url;
44
+ } catch (error) {
45
+ throw new RestApiError({
46
+ name: RestApiValidationErrorCode.InvalidApiName,
47
+ ...validationErrorMap[RestApiValidationErrorCode.InvalidApiName],
48
+ recoverySuggestion: `Please make sure the REST endpoint URL is a valid URL string. Got ${urlStr}`,
49
+ });
50
+ }
51
+ };
@@ -0,0 +1,17 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { AmplifyClassV6 } from '@aws-amplify/core';
5
+ import { RestApiValidationErrorCode, assertValidationError } from '../errors';
6
+
7
+ /**
8
+ * @internal
9
+ */
10
+ export const resolveCredentials = async (amplify: AmplifyClassV6) => {
11
+ const { credentials } = await amplify.Auth.fetchAuthSession();
12
+ assertValidationError(
13
+ !!credentials && !!credentials.accessKeyId && !!credentials.secretAccessKey,
14
+ RestApiValidationErrorCode.NoCredentials
15
+ );
16
+ return credentials;
17
+ };
@@ -0,0 +1,35 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { MetadataBearer } from '@aws-sdk/types';
4
+ import {
5
+ HttpResponse,
6
+ parseJsonError,
7
+ } from '@aws-amplify/core/internals/aws-client-utils';
8
+ import { RestApiError } from '../errors';
9
+
10
+ /**
11
+ * Internal-only method to create a new RestApiError from a service error.
12
+ *
13
+ * @internal
14
+ */
15
+ export const buildRestApiServiceError = (error: Error): RestApiError => {
16
+ const restApiError = new RestApiError({
17
+ name: error?.name,
18
+ message: error.message,
19
+ underlyingError: error,
20
+ });
21
+ return restApiError;
22
+ };
23
+
24
+ export const parseRestApiServiceError = async (
25
+ response?: HttpResponse
26
+ ): Promise<(RestApiError & MetadataBearer) | undefined> => {
27
+ const parsedError = await parseJsonError(response);
28
+ if (!parsedError) {
29
+ // Response is not an error.
30
+ return;
31
+ }
32
+ return Object.assign(buildRestApiServiceError(parsedError), {
33
+ $metadata: parsedError.$metadata,
34
+ });
35
+ };
package/lib/.tsbuildinfo DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "version": "3.8.3"
3
- }
package/lib/RestAPI.d.ts DELETED
@@ -1,108 +0,0 @@
1
- /**
2
- * Export Cloud Logic APIs
3
- */
4
- export declare class RestAPIClass {
5
- /**
6
- * @private
7
- */
8
- private _options;
9
- private _api;
10
- Credentials: import("@aws-amplify/core").CredentialsClass;
11
- /**
12
- * Initialize Rest API with AWS configuration
13
- * @param {Object} options - Configuration object for API
14
- */
15
- constructor(options: any);
16
- getModuleName(): string;
17
- /**
18
- * Configure API part with aws configurations
19
- * @param {Object} config - Configuration of the API
20
- * @return {Object} - The current configuration
21
- */
22
- configure(options: any): any;
23
- /**
24
- * Create an instance of API for the library
25
- * @return - A promise of true if Success
26
- */
27
- createInstance(): boolean;
28
- /**
29
- * Make a GET request
30
- * @param {string} apiName - The api name of the request
31
- * @param {string} path - The path of the request
32
- * @param {json} [init] - Request extra params
33
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
34
- */
35
- get(apiName: any, path: any, init: any): Promise<any>;
36
- /**
37
- * Make a POST request
38
- * @param {string} apiName - The api name of the request
39
- * @param {string} path - The path of the request
40
- * @param {json} [init] - Request extra params
41
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
42
- */
43
- post(apiName: any, path: any, init: any): Promise<any>;
44
- /**
45
- * Make a PUT request
46
- * @param {string} apiName - The api name of the request
47
- * @param {string} path - The path of the request
48
- * @param {json} [init] - Request extra params
49
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
50
- */
51
- put(apiName: any, path: any, init: any): Promise<any>;
52
- /**
53
- * Make a PATCH request
54
- * @param {string} apiName - The api name of the request
55
- * @param {string} path - The path of the request
56
- * @param {json} [init] - Request extra params
57
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
58
- */
59
- patch(apiName: any, path: any, init: any): Promise<any>;
60
- /**
61
- * Make a DEL request
62
- * @param {string} apiName - The api name of the request
63
- * @param {string} path - The path of the request
64
- * @param {json} [init] - Request extra params
65
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
66
- */
67
- del(apiName: any, path: any, init: any): Promise<any>;
68
- /**
69
- * Make a HEAD request
70
- * @param {string} apiName - The api name of the request
71
- * @param {string} path - The path of the request
72
- * @param {json} [init] - Request extra params
73
- * @return {Promise} - A promise that resolves to an object with response status and JSON data, if successful.
74
- */
75
- head(apiName: any, path: any, init: any): Promise<any>;
76
- /**
77
- * Checks to see if an error thrown is from an api request cancellation
78
- * @param {any} error - Any error
79
- * @return {boolean} - A boolean indicating if the error was from an api request cancellation
80
- */
81
- isCancel(error: any): boolean;
82
- /**
83
- * Cancels an inflight request
84
- * @param {any} request - request to cancel
85
- * @return {boolean} - A boolean indicating if the request was cancelled
86
- */
87
- cancel(request: Promise<any>, message?: string): boolean;
88
- /**
89
- * Check if the request has a corresponding cancel token in the WeakMap.
90
- * @params request - The request promise
91
- * @return if the request has a corresponding cancel token.
92
- */
93
- hasCancelToken(request: Promise<any>): boolean;
94
- /**
95
- * Getting endpoint for API
96
- * @param {string} apiName - The name of the api
97
- * @return {string} - The endpoint of the api
98
- */
99
- endpoint(apiName: any): Promise<string>;
100
- /**
101
- * Getting endpoint info for API
102
- * @param {string} apiName - The name of the api
103
- * @param {string} path - The path of the api that is going to accessed
104
- * @return {ApiInfo} - The endpoint information for that api-name
105
- */
106
- private getEndpointInfo;
107
- }
108
- export declare const RestAPI: RestAPIClass;