@aws-amplify/api-graphql 3.4.12-api-v6-models.b3abc9b.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 (118) hide show
  1. package/README.md +3 -0
  2. package/lib/GraphQLAPI.d.ts +17 -4
  3. package/lib/GraphQLAPI.js +33 -27
  4. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  5. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +690 -0
  6. package/lib/Providers/constants.d.ts +95 -0
  7. package/lib/Providers/constants.js +103 -0
  8. package/lib/index.d.ts +1 -3
  9. package/lib/index.js +6 -10
  10. package/lib/internals/InternalGraphQLAPI.d.ts +11 -34
  11. package/lib/internals/InternalGraphQLAPI.js +219 -345
  12. package/lib/internals/index.d.ts +1 -1
  13. package/lib/internals/index.js +2 -1
  14. package/lib/internals/v6.d.ts +14 -2
  15. package/lib/internals/v6.js +21 -3
  16. package/lib/tsconfig.tsbuildinfo +6813 -0
  17. package/lib/types/PubSub.d.ts +27 -0
  18. package/lib/types/PubSub.js +46 -0
  19. package/lib/types/index.d.ts +119 -12
  20. package/lib/types/index.js +4 -3
  21. package/lib/utils/ConnectionStateMonitor.d.ts +41 -0
  22. package/lib/utils/ConnectionStateMonitor.js +131 -0
  23. package/lib/utils/ReachabilityMonitor/index.d.ts +1 -0
  24. package/lib/utils/ReachabilityMonitor/index.js +6 -0
  25. package/lib/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  26. package/lib/utils/ReachabilityMonitor/index.native.js +8 -0
  27. package/lib/utils/ReconnectionMonitor.d.ts +29 -0
  28. package/lib/utils/ReconnectionMonitor.js +68 -0
  29. package/lib/utils/errors/APIError.d.ts +7 -0
  30. package/lib/utils/errors/APIError.js +18 -0
  31. package/lib/utils/errors/assertValidationError.d.ts +5 -0
  32. package/lib/utils/errors/assertValidationError.js +16 -0
  33. package/lib/utils/errors/index.d.ts +3 -0
  34. package/lib/utils/errors/index.js +11 -0
  35. package/lib/utils/errors/validation.d.ts +7 -0
  36. package/lib/utils/errors/validation.js +25 -0
  37. package/lib/utils/index.d.ts +2 -0
  38. package/lib/utils/index.js +8 -0
  39. package/lib/utils/resolveConfig.d.ts +12 -0
  40. package/lib/utils/resolveConfig.js +22 -0
  41. package/lib/utils/resolveLibraryOptions.d.ts +11 -0
  42. package/lib/utils/resolveLibraryOptions.js +12 -0
  43. package/lib-esm/GraphQLAPI.d.ts +17 -4
  44. package/lib-esm/GraphQLAPI.js +33 -28
  45. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  46. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +687 -0
  47. package/lib-esm/Providers/constants.d.ts +95 -0
  48. package/lib-esm/Providers/constants.js +100 -0
  49. package/lib-esm/index.d.ts +1 -3
  50. package/lib-esm/index.js +1 -4
  51. package/lib-esm/internals/InternalGraphQLAPI.d.ts +11 -34
  52. package/lib-esm/internals/InternalGraphQLAPI.js +218 -345
  53. package/lib-esm/internals/index.d.ts +1 -1
  54. package/lib-esm/internals/index.js +1 -2
  55. package/lib-esm/internals/v6.d.ts +14 -2
  56. package/lib-esm/internals/v6.js +18 -2
  57. package/lib-esm/tsconfig.tsbuildinfo +6813 -0
  58. package/lib-esm/types/PubSub.d.ts +27 -0
  59. package/lib-esm/types/PubSub.js +44 -0
  60. package/lib-esm/types/index.d.ts +119 -12
  61. package/lib-esm/types/index.js +2 -3
  62. package/lib-esm/utils/ConnectionStateMonitor.d.ts +41 -0
  63. package/lib-esm/utils/ConnectionStateMonitor.js +128 -0
  64. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +1 -0
  65. package/lib-esm/utils/ReachabilityMonitor/index.js +4 -0
  66. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  67. package/lib-esm/utils/ReachabilityMonitor/index.native.js +5 -0
  68. package/lib-esm/utils/ReconnectionMonitor.d.ts +29 -0
  69. package/lib-esm/utils/ReconnectionMonitor.js +65 -0
  70. package/lib-esm/utils/errors/APIError.d.ts +7 -0
  71. package/lib-esm/utils/errors/APIError.js +15 -0
  72. package/lib-esm/utils/errors/assertValidationError.d.ts +5 -0
  73. package/lib-esm/utils/errors/assertValidationError.js +13 -0
  74. package/lib-esm/utils/errors/index.d.ts +3 -0
  75. package/lib-esm/utils/errors/index.js +5 -0
  76. package/lib-esm/utils/errors/validation.d.ts +7 -0
  77. package/lib-esm/utils/errors/validation.js +23 -0
  78. package/lib-esm/utils/index.d.ts +2 -0
  79. package/lib-esm/utils/index.js +4 -0
  80. package/lib-esm/utils/resolveConfig.d.ts +12 -0
  81. package/lib-esm/utils/resolveConfig.js +20 -0
  82. package/lib-esm/utils/resolveLibraryOptions.d.ts +11 -0
  83. package/lib-esm/utils/resolveLibraryOptions.js +10 -0
  84. package/package.json +122 -118
  85. package/src/GraphQLAPI.ts +26 -4
  86. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +998 -0
  87. package/src/Providers/constants.ts +110 -0
  88. package/src/index.ts +2 -3
  89. package/src/internals/InternalGraphQLAPI.ts +181 -218
  90. package/src/internals/index.ts +1 -1
  91. package/src/internals/v6.ts +34 -2
  92. package/src/types/PubSub.ts +56 -0
  93. package/src/types/index.ts +175 -15
  94. package/src/utils/ConnectionStateMonitor.ts +199 -0
  95. package/src/utils/ReachabilityMonitor/index.native.ts +7 -0
  96. package/src/utils/ReachabilityMonitor/index.ts +4 -0
  97. package/src/utils/ReconnectionMonitor.ts +76 -0
  98. package/src/utils/errors/APIError.ts +21 -0
  99. package/src/utils/errors/assertValidationError.ts +19 -0
  100. package/src/utils/errors/index.ts +6 -0
  101. package/src/utils/errors/validation.ts +26 -0
  102. package/src/utils/index.ts +5 -0
  103. package/src/utils/resolveConfig.ts +35 -0
  104. package/src/utils/resolveLibraryOptions.ts +13 -0
  105. package/lib/.tsbuildinfo +0 -3
  106. package/lib/GraphQLAPI.js.map +0 -1
  107. package/lib/index.js.map +0 -1
  108. package/lib/internals/InternalGraphQLAPI.js.map +0 -1
  109. package/lib/internals/index.js.map +0 -1
  110. package/lib/internals/v6.js.map +0 -1
  111. package/lib/types/index.js.map +0 -1
  112. package/lib-esm/.tsbuildinfo +0 -3
  113. package/lib-esm/GraphQLAPI.js.map +0 -1
  114. package/lib-esm/index.js.map +0 -1
  115. package/lib-esm/internals/InternalGraphQLAPI.js.map +0 -1
  116. package/lib-esm/internals/index.js.map +0 -1
  117. package/lib-esm/internals/v6.js.map +0 -1
  118. package/lib-esm/types/index.js.map +0 -1
@@ -0,0 +1,110 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ export { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';
4
+
5
+ export const MAX_DELAY_MS = 5000;
6
+
7
+ export const NON_RETRYABLE_CODES = [400, 401, 403];
8
+
9
+ export const CONNECTION_STATE_CHANGE = 'ConnectionStateChange';
10
+
11
+ export enum MESSAGE_TYPES {
12
+ /**
13
+ * Client -> Server message.
14
+ * This message type is the first message after handshake and this will initialize AWS AppSync RealTime communication
15
+ */
16
+ GQL_CONNECTION_INIT = 'connection_init',
17
+ /**
18
+ * Server -> Client message
19
+ * This message type is in case there is an issue with AWS AppSync RealTime when establishing connection
20
+ */
21
+ GQL_CONNECTION_ERROR = 'connection_error',
22
+ /**
23
+ * Server -> Client message.
24
+ * This message type is for the ack response from AWS AppSync RealTime for GQL_CONNECTION_INIT message
25
+ */
26
+ GQL_CONNECTION_ACK = 'connection_ack',
27
+ /**
28
+ * Client -> Server message.
29
+ * This message type is for register subscriptions with AWS AppSync RealTime
30
+ */
31
+ GQL_START = 'start',
32
+ /**
33
+ * Server -> Client message.
34
+ * This message type is for the ack response from AWS AppSync RealTime for GQL_START message
35
+ */
36
+ GQL_START_ACK = 'start_ack',
37
+ /**
38
+ * Server -> Client message.
39
+ * This message type is for subscription message from AWS AppSync RealTime
40
+ */
41
+ GQL_DATA = 'data',
42
+ /**
43
+ * Server -> Client message.
44
+ * This message type helps the client to know is still receiving messages from AWS AppSync RealTime
45
+ */
46
+ GQL_CONNECTION_KEEP_ALIVE = 'ka',
47
+ /**
48
+ * Client -> Server message.
49
+ * This message type is for unregister subscriptions with AWS AppSync RealTime
50
+ */
51
+ GQL_STOP = 'stop',
52
+ /**
53
+ * Server -> Client message.
54
+ * This message type is for the ack response from AWS AppSync RealTime for GQL_STOP message
55
+ */
56
+ GQL_COMPLETE = 'complete',
57
+ /**
58
+ * Server -> Client message.
59
+ * This message type is for sending error messages from AWS AppSync RealTime to the client
60
+ */
61
+ GQL_ERROR = 'error', // Server -> Client
62
+ }
63
+
64
+ export enum SUBSCRIPTION_STATUS {
65
+ PENDING,
66
+ CONNECTED,
67
+ FAILED,
68
+ }
69
+
70
+ export enum SOCKET_STATUS {
71
+ CLOSED,
72
+ READY,
73
+ CONNECTING,
74
+ }
75
+
76
+ export const AWS_APPSYNC_REALTIME_HEADERS = {
77
+ accept: 'application/json, text/javascript',
78
+ 'content-encoding': 'amz-1.0',
79
+ 'content-type': 'application/json; charset=UTF-8',
80
+ };
81
+
82
+ /**
83
+ * Time in milleseconds to wait for GQL_CONNECTION_INIT message
84
+ */
85
+ export const CONNECTION_INIT_TIMEOUT = 15000;
86
+
87
+ /**
88
+ * Time in milleseconds to wait for GQL_START_ACK message
89
+ */
90
+ export const START_ACK_TIMEOUT = 15000;
91
+
92
+ /**
93
+ * Default Time in milleseconds to wait for GQL_CONNECTION_KEEP_ALIVE message
94
+ */
95
+ export const DEFAULT_KEEP_ALIVE_TIMEOUT = 5 * 60 * 1000;
96
+
97
+ /**
98
+ * Default Time in milleseconds to alert for missed GQL_CONNECTION_KEEP_ALIVE message
99
+ */
100
+ export const DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT = 65 * 1000;
101
+
102
+ /**
103
+ * Default delay time in milleseconds between when reconnect is triggered vs when it is attempted
104
+ */
105
+ export const RECONNECT_DELAY = 5 * 1000;
106
+
107
+ /**
108
+ * Default interval time in milleseconds between when reconnect is re-attempted
109
+ */
110
+ export const RECONNECT_INTERVAL = 60 * 1000;
package/src/index.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import { GraphQLAPI } from './GraphQLAPI';
5
- export { GraphQLResult, GraphQLAuthError, GRAPHQL_AUTH_MODE } from './types';
6
4
  export { GraphQLAPI, GraphQLAPIClass, graphqlOperation } from './GraphQLAPI';
7
5
  export * from './types';
8
- export default GraphQLAPI;
6
+
7
+ export { CONNECTION_STATE_CHANGE } from './Providers/constants';
@@ -8,28 +8,32 @@ import {
8
8
  GraphQLError,
9
9
  OperationTypeNode,
10
10
  } from 'graphql';
11
- import Observable from 'zen-observable-ts';
11
+ import { Observable } from 'rxjs';
12
+ import { AmplifyClassV6, ConsoleLogger } from '@aws-amplify/core';
12
13
  import {
13
- Amplify,
14
- ConsoleLogger as Logger,
15
- Credentials,
14
+ GraphQLAuthMode,
16
15
  CustomUserAgentDetails,
17
16
  getAmplifyUserAgent,
18
- INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER,
19
- } from '@aws-amplify/core';
20
- import { InternalPubSub } from '@aws-amplify/pubsub/internals';
21
- import { Auth } from '@aws-amplify/auth';
22
- import { Cache } from '@aws-amplify/cache';
17
+ AmplifyUrl,
18
+ } from '@aws-amplify/core/internals/utils';
23
19
  import {
24
20
  GraphQLAuthError,
25
- GraphQLOptions,
26
21
  GraphQLResult,
27
22
  GraphQLOperation,
23
+ GraphQLOptions,
28
24
  } from '../types';
29
- import { RestClient } from '@aws-amplify/api-rest';
25
+ import { isCancelError as isCancelErrorREST } from '@aws-amplify/api-rest';
26
+ import {
27
+ post,
28
+ cancel as cancelREST,
29
+ updateRequestToBeCancellable,
30
+ } from '@aws-amplify/api-rest/internals';
31
+ import { AWSAppSyncRealTimeProvider } from '../Providers/AWSAppSyncRealTimeProvider';
32
+ import { resolveConfig, resolveLibraryOptions } from '../utils';
33
+
30
34
  const USER_AGENT_HEADER = 'x-amz-user-agent';
31
35
 
32
- const logger = new Logger('GraphQLAPI');
36
+ const logger = new ConsoleLogger('GraphQLAPI');
33
37
 
34
38
  export const graphqlOperation = (
35
39
  query,
@@ -41,6 +45,10 @@ export const graphqlOperation = (
41
45
  authToken,
42
46
  });
43
47
 
48
+ const isAmplifyInstance = (amplify): amplify is AmplifyClassV6 => {
49
+ return typeof amplify !== 'function';
50
+ };
51
+
44
52
  /**
45
53
  * Export Cloud Logic APIs
46
54
  */
@@ -49,11 +57,14 @@ export class InternalGraphQLAPIClass {
49
57
  * @private
50
58
  */
51
59
  private _options;
52
- private _api = null;
60
+ private appSyncRealTime: AWSAppSyncRealTimeProvider | null;
53
61
 
54
- Auth = Auth;
55
- Cache = Cache;
56
- Credentials = Credentials;
62
+ private _api = {
63
+ post,
64
+ cancelREST,
65
+ isCancelErrorREST,
66
+ updateRequestToBeCancellable,
67
+ };
57
68
 
58
69
  /**
59
70
  * Initialize GraphQL API with AWS configuration
@@ -68,94 +79,46 @@ export class InternalGraphQLAPIClass {
68
79
  return 'InternalGraphQLAPI';
69
80
  }
70
81
 
71
- /**
72
- * Configure API
73
- * @param {Object} config - Configuration of the API
74
- * @return {Object} - The current configuration
75
- */
76
- configure(options) {
77
- const { API = {}, ...otherOptions } = options || {};
78
- let opt = { ...otherOptions, ...API };
79
- logger.debug('configure GraphQL API', { opt });
80
-
81
- if (opt['aws_project_region']) {
82
- opt = Object.assign({}, opt, {
83
- region: opt['aws_project_region'],
84
- header: {},
85
- });
86
- }
87
-
88
- if (
89
- typeof opt.graphql_headers !== 'undefined' &&
90
- typeof opt.graphql_headers !== 'function'
91
- ) {
92
- logger.warn('graphql_headers should be a function');
93
- opt.graphql_headers = undefined;
94
- }
95
-
96
- this._options = Object.assign({}, this._options, opt);
97
-
98
- this.createInstance();
99
-
100
- return this._options;
101
- }
102
-
103
- /**
104
- * Create an instance of API for the library
105
- * @return - A promise of true if Success
106
- */
107
- createInstance() {
108
- logger.debug('create Rest instance');
109
- if (this._options) {
110
- this._api = new RestClient(this._options);
111
- // Share instance Credentials with client for SSR
112
- this._api.Credentials = this.Credentials;
113
-
114
- return true;
115
- } else {
116
- return Promise.reject('API not configured');
117
- }
118
- }
119
-
120
82
  private async _headerBasedAuth(
121
- defaultAuthenticationType?,
83
+ amplify: AmplifyClassV6,
84
+ authMode: GraphQLAuthMode,
122
85
  additionalHeaders: { [key: string]: string } = {}
123
86
  ) {
124
- const { aws_appsync_authenticationType, aws_appsync_apiKey: apiKey } =
125
- this._options;
126
- const authenticationType =
127
- defaultAuthenticationType || aws_appsync_authenticationType || 'AWS_IAM';
87
+ const config = amplify.getConfig();
88
+ const {
89
+ region: region,
90
+ endpoint: appSyncGraphqlEndpoint,
91
+ apiKey,
92
+ defaultAuthMode,
93
+ } = resolveConfig(amplify);
94
+
95
+ const authenticationType = authMode || defaultAuthMode || 'iam';
128
96
  let headers = {};
129
97
 
130
98
  switch (authenticationType) {
131
- case 'API_KEY':
99
+ case 'apiKey':
132
100
  if (!apiKey) {
133
101
  throw new Error(GraphQLAuthError.NO_API_KEY);
134
102
  }
135
103
  headers = {
136
- Authorization: null,
137
104
  'X-Api-Key': apiKey,
138
105
  };
139
106
  break;
140
- case 'AWS_IAM':
141
- const credentialsOK = await this._ensureCredentials();
142
- if (!credentialsOK) {
107
+ case 'iam':
108
+ const session = await amplify.Auth.fetchAuthSession();
109
+ if (session.credentials === undefined) {
143
110
  throw new Error(GraphQLAuthError.NO_CREDENTIALS);
144
111
  }
145
112
  break;
146
- case 'OPENID_CONNECT':
113
+ case 'oidc':
114
+ case 'userPool':
147
115
  try {
148
116
  let token;
149
- // backwards compatibility
150
- const federatedInfo = await Cache.getItem('federatedInfo');
151
- if (federatedInfo) {
152
- token = federatedInfo.token;
153
- } else {
154
- const currentUser = await Auth.currentAuthenticatedUser();
155
- if (currentUser) {
156
- token = currentUser.token;
157
- }
158
- }
117
+
118
+ token = (
119
+ await amplify.Auth.fetchAuthSession()
120
+ ).tokens?.accessToken.toString();
121
+
159
122
  if (!token) {
160
123
  throw new Error(GraphQLAuthError.NO_FEDERATED_JWT);
161
124
  }
@@ -166,17 +129,7 @@ export class InternalGraphQLAPIClass {
166
129
  throw new Error(GraphQLAuthError.NO_CURRENT_USER);
167
130
  }
168
131
  break;
169
- case 'AMAZON_COGNITO_USER_POOLS':
170
- try {
171
- const session = await this.Auth.currentSession();
172
- headers = {
173
- Authorization: session.getAccessToken().getJwtToken(),
174
- };
175
- } catch (e) {
176
- throw new Error(GraphQLAuthError.NO_CURRENT_USER);
177
- }
178
- break;
179
- case 'AWS_LAMBDA':
132
+ case 'lambda':
180
133
  if (!additionalHeaders.Authorization) {
181
134
  throw new Error(GraphQLAuthError.NO_AUTH_TOKEN);
182
135
  }
@@ -184,10 +137,9 @@ export class InternalGraphQLAPIClass {
184
137
  Authorization: additionalHeaders.Authorization,
185
138
  };
186
139
  break;
140
+ case 'none':
141
+ break;
187
142
  default:
188
- headers = {
189
- Authorization: null,
190
- };
191
143
  break;
192
144
  }
193
145
 
@@ -215,6 +167,9 @@ export class InternalGraphQLAPIClass {
215
167
  * @returns An Observable if the query is a subscription query, else a promise of the graphql result.
216
168
  */
217
169
  graphql<T = any>(
170
+ amplify:
171
+ | AmplifyClassV6
172
+ | ((fn: (amplify: any) => Promise<any>) => Promise<AmplifyClassV6>),
218
173
  { query: paramQuery, variables = {}, authMode, authToken }: GraphQLOptions,
219
174
  additionalHeaders?: { [key: string]: string },
220
175
  customUserAgentDetails?: CustomUserAgentDetails
@@ -240,25 +195,41 @@ export class InternalGraphQLAPIClass {
240
195
  switch (operationType) {
241
196
  case 'query':
242
197
  case 'mutation':
243
- this.createInstanceIfNotCreated();
244
- const cancellableToken = this._api.getCancellableToken();
245
- const initParams = {
246
- cancellableToken,
247
- withCredentials: this._options.withCredentials,
248
- };
249
- const responsePromise = this._graphql<T>(
250
- { query, variables, authMode },
251
- headers,
252
- initParams,
253
- customUserAgentDetails
254
- );
198
+ const abortController = new AbortController();
199
+
200
+ let responsePromise: Promise<GraphQLResult<T>>;
201
+
202
+ if (isAmplifyInstance(amplify)) {
203
+ responsePromise = this._graphql<T>(
204
+ amplify,
205
+ { query, variables, authMode },
206
+ headers,
207
+ abortController,
208
+ customUserAgentDetails
209
+ );
210
+ } else {
211
+ const wrapper = amplifyInstance =>
212
+ this._graphql<T>(
213
+ amplifyInstance,
214
+ { query, variables, authMode },
215
+ headers,
216
+ abortController,
217
+ customUserAgentDetails
218
+ );
219
+
220
+ responsePromise = amplify(wrapper) as unknown as Promise<
221
+ GraphQLResult<T>
222
+ >;
223
+ }
224
+
255
225
  this._api.updateRequestToBeCancellable(
256
226
  responsePromise,
257
- cancellableToken
227
+ abortController
258
228
  );
259
229
  return responsePromise;
260
230
  case 'subscription':
261
231
  return this._graphqlSubscribe(
232
+ amplify as AmplifyClassV6,
262
233
  { query, variables, authMode },
263
234
  headers,
264
235
  customUserAgentDetails
@@ -269,52 +240,82 @@ export class InternalGraphQLAPIClass {
269
240
  }
270
241
 
271
242
  private async _graphql<T = any>(
243
+ amplify: AmplifyClassV6,
272
244
  { query, variables, authMode }: GraphQLOptions,
273
245
  additionalHeaders = {},
274
- initParams = {},
246
+ abortController: AbortController,
275
247
  customUserAgentDetails?: CustomUserAgentDetails
276
248
  ): Promise<GraphQLResult<T>> {
277
- this.createInstanceIfNotCreated();
278
249
  const {
279
- aws_appsync_region: region,
280
- aws_appsync_graphqlEndpoint: appSyncGraphqlEndpoint,
281
- graphql_headers = () => ({}),
282
- graphql_endpoint: customGraphqlEndpoint,
283
- graphql_endpoint_iam_region: customEndpointRegion,
284
- } = this._options;
250
+ region: region,
251
+ endpoint: appSyncGraphqlEndpoint,
252
+ customEndpoint,
253
+ customEndpointRegion,
254
+ } = resolveConfig(amplify);
255
+
256
+ // Retrieve library options from Amplify configuration
257
+ const { headers: customHeaders, withCredentials } =
258
+ resolveLibraryOptions(amplify);
285
259
 
260
+ // TODO: Figure what we need to do to remove `!`'s.
286
261
  const headers = {
287
- ...(!customGraphqlEndpoint &&
288
- (await this._headerBasedAuth(authMode, additionalHeaders))),
289
- ...(customGraphqlEndpoint &&
262
+ ...(!customEndpoint &&
263
+ (await this._headerBasedAuth(amplify, authMode!, additionalHeaders))),
264
+ /**
265
+ * Custom endpoint headers.
266
+ * If there is both a custom endpoint and custom region present, we get the headers.
267
+ * If there is a custom endpoint but no region, we return an empty object.
268
+ * If neither are present, we return an empty object.
269
+ */
270
+ ...((customEndpoint &&
290
271
  (customEndpointRegion
291
- ? await this._headerBasedAuth(authMode, additionalHeaders)
292
- : { Authorization: null })),
293
- ...(await graphql_headers({ query, variables })),
272
+ ? await this._headerBasedAuth(amplify, authMode!, additionalHeaders)
273
+ : {})) ||
274
+ {}),
275
+ // Custom headers included in Amplify configuration options:
276
+ ...(customHeaders &&
277
+ (await customHeaders({
278
+ query: print(query as DocumentNode),
279
+ variables,
280
+ }))),
281
+ // Headers from individual calls to `graphql`:
294
282
  ...additionalHeaders,
295
- ...(!customGraphqlEndpoint && {
283
+ // User agent headers:
284
+ ...(!customEndpoint && {
296
285
  [USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),
297
286
  }),
298
287
  };
299
288
 
300
289
  const body = {
301
290
  query: print(query as DocumentNode),
302
- variables,
291
+ variables: variables || null,
303
292
  };
304
293
 
305
- const init = Object.assign(
306
- {
307
- headers,
308
- body,
309
- signerServiceInfo: {
310
- service: !customGraphqlEndpoint ? 'appsync' : 'execute-api',
311
- region: !customGraphqlEndpoint ? region : customEndpointRegion,
312
- },
313
- },
314
- initParams
315
- );
294
+ let signingServiceInfo;
295
+
296
+ /**
297
+ * We do not send the signing service info to the REST API under the
298
+ * following conditions (i.e. it will not sign the request):
299
+ * - there is a custom endpoint but no region
300
+ * - the auth mode is `none`, or `apiKey`
301
+ * - the auth mode is a type other than the types listed below
302
+ */
303
+ if (
304
+ (customEndpoint && !customEndpointRegion) ||
305
+ (authMode !== 'oidc' &&
306
+ authMode !== 'userPool' &&
307
+ authMode !== 'iam' &&
308
+ authMode !== 'lambda')
309
+ ) {
310
+ signingServiceInfo = null;
311
+ } else {
312
+ signingServiceInfo = {
313
+ service: !customEndpointRegion ? 'appsync' : 'execute-api',
314
+ region: !customEndpointRegion ? region : customEndpointRegion,
315
+ };
316
+ }
316
317
 
317
- const endpoint = customGraphqlEndpoint || appSyncGraphqlEndpoint;
318
+ const endpoint = customEndpoint || appSyncGraphqlEndpoint;
318
319
 
319
320
  if (!endpoint) {
320
321
  const error = new GraphQLError('No graphql endpoint provided.');
@@ -327,14 +328,28 @@ export class InternalGraphQLAPIClass {
327
328
 
328
329
  let response;
329
330
  try {
330
- response = await this._api.post(endpoint, init);
331
+ const { body: responseBody } = await this._api.post({
332
+ url: new AmplifyUrl(endpoint),
333
+ options: {
334
+ headers,
335
+ body,
336
+ signingServiceInfo,
337
+ withCredentials,
338
+ },
339
+ abortController,
340
+ });
341
+
342
+ const result = await responseBody.json();
343
+
344
+ response = result;
331
345
  } catch (err) {
332
346
  // If the exception is because user intentionally
333
347
  // cancelled the request, do not modify the exception
334
348
  // so that clients can identify the exception correctly.
335
- if (this._api.isCancel(err)) {
349
+ if (this.isCancelError(err)) {
336
350
  throw err;
337
351
  }
352
+
338
353
  response = {
339
354
  data: {},
340
355
  errors: [new GraphQLError(err.message, null, null, null, null, err)],
@@ -350,100 +365,48 @@ export class InternalGraphQLAPIClass {
350
365
  return response;
351
366
  }
352
367
 
353
- async createInstanceIfNotCreated() {
354
- if (!this._api) {
355
- await this.createInstance();
356
- }
357
- }
358
-
359
368
  /**
360
369
  * Checks to see if an error thrown is from an api request cancellation
361
370
  * @param {any} error - Any error
362
371
  * @return {boolean} - A boolean indicating if the error was from an api request cancellation
363
372
  */
364
- isCancel(error) {
365
- return this._api.isCancel(error);
373
+ isCancelError(error: any): boolean {
374
+ return this._api.isCancelErrorREST(error);
366
375
  }
367
376
 
368
377
  /**
369
378
  * Cancels an inflight request. Only applicable for graphql queries and mutations
370
379
  * @param {any} request - request to cancel
371
- * @return {boolean} - A boolean indicating if the request was cancelled
372
- */
373
- cancel(request: Promise<any>, message?: string) {
374
- return this._api.cancel(request, message);
375
- }
376
-
377
- /**
378
- * Check if the request has a corresponding cancel token in the WeakMap.
379
- * @params request - The request promise
380
- * @return if the request has a corresponding cancel token.
380
+ * @returns - A boolean indicating if the request was cancelled
381
381
  */
382
- hasCancelToken(request: Promise<any>) {
383
- return this._api.hasCancelToken(request);
382
+ cancel(request: Promise<any>, message?: string): boolean {
383
+ return this._api.cancelREST(request, message);
384
384
  }
385
385
 
386
386
  private _graphqlSubscribe(
387
- {
388
- query,
389
- variables,
390
- authMode: defaultAuthenticationType,
391
- authToken,
392
- }: GraphQLOptions,
387
+ amplify: AmplifyClassV6,
388
+ { query, variables, authMode }: GraphQLOptions,
393
389
  additionalHeaders = {},
394
390
  customUserAgentDetails?: CustomUserAgentDetails
395
391
  ): Observable<any> {
396
- const {
397
- aws_appsync_region: region,
398
- aws_appsync_graphqlEndpoint: appSyncGraphqlEndpoint,
399
- aws_appsync_authenticationType,
400
- aws_appsync_apiKey: apiKey,
401
- graphql_headers = () => ({}),
402
- } = this._options;
403
- const authenticationType =
404
- defaultAuthenticationType || aws_appsync_authenticationType || 'AWS_IAM';
405
-
406
- if (InternalPubSub && typeof InternalPubSub.subscribe === 'function') {
407
- return InternalPubSub.subscribe(
408
- '',
409
- {
410
- provider: INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER,
411
- appSyncGraphqlEndpoint,
412
- authenticationType,
413
- apiKey,
414
- query: print(query as DocumentNode),
415
- region,
416
- variables,
417
- graphql_headers,
418
- additionalHeaders,
419
- authToken,
420
- },
421
- customUserAgentDetails
422
- );
423
- } else {
424
- logger.debug('No pubsub module applied for subscription');
425
- throw new Error('No pubsub module applied for subscription');
426
- }
427
- }
392
+ const config = resolveConfig(amplify);
428
393
 
429
- /**
430
- * @private
431
- */
432
- _ensureCredentials() {
433
- return this.Credentials.get()
434
- .then(credentials => {
435
- if (!credentials) return false;
436
- const cred = this.Credentials.shear(credentials);
437
- logger.debug('set credentials for api', cred);
438
-
439
- return true;
440
- })
441
- .catch(err => {
442
- logger.warn('ensure credentials error', err);
443
- return false;
444
- });
394
+ if (!this.appSyncRealTime) {
395
+ this.appSyncRealTime = new AWSAppSyncRealTimeProvider();
396
+ }
397
+ return this.appSyncRealTime.subscribe(
398
+ {
399
+ query: print(query as DocumentNode),
400
+ variables,
401
+ appSyncGraphqlEndpoint: config?.endpoint,
402
+ region: config?.region,
403
+ authenticationType: authMode ?? config?.defaultAuthMode,
404
+ apiKey: config?.apiKey,
405
+ additionalHeaders,
406
+ },
407
+ customUserAgentDetails
408
+ );
445
409
  }
446
410
  }
447
411
 
448
412
  export const InternalGraphQLAPI = new InternalGraphQLAPIClass(null);
449
- Amplify.register(InternalGraphQLAPI);
@@ -5,4 +5,4 @@ export {
5
5
  InternalGraphQLAPIClass,
6
6
  } from './InternalGraphQLAPI';
7
7
 
8
- export { graphql } from './v6';
8
+ export { graphql, cancel, isCancelError } from './v6';