@aws-amplify/api-graphql 3.4.11 → 4.0.1-console-preview.047a1dd.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 (114) hide show
  1. package/README.md +3 -0
  2. package/lib/GraphQLAPI.js +0 -5
  3. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +67 -0
  4. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +817 -0
  5. package/lib/Providers/constants.d.ts +95 -0
  6. package/lib/Providers/constants.js +103 -0
  7. package/lib/index.d.ts +0 -3
  8. package/lib/index.js +3 -9
  9. package/lib/internals/InternalGraphQLAPI.d.ts +4 -40
  10. package/lib/internals/InternalGraphQLAPI.js +89 -243
  11. package/lib/internals/index.d.ts +1 -0
  12. package/lib/internals/index.js +2 -1
  13. package/lib/internals/v6.d.ts +89 -0
  14. package/lib/internals/v6.js +99 -0
  15. package/lib/tsconfig.tsbuildinfo +5790 -0
  16. package/lib/types/PubSub.d.ts +27 -0
  17. package/lib/types/PubSub.js +46 -0
  18. package/lib/types/index.d.ts +184 -4
  19. package/lib/types/index.js +0 -3
  20. package/lib/utils/ConnectionStateMonitor.d.ts +41 -0
  21. package/lib/utils/ConnectionStateMonitor.js +143 -0
  22. package/lib/utils/ReachabilityMonitor/index.d.ts +3 -0
  23. package/lib/utils/ReachabilityMonitor/index.js +6 -0
  24. package/lib/utils/ReachabilityMonitor/index.native.d.ts +3 -0
  25. package/lib/utils/ReachabilityMonitor/index.native.js +10 -0
  26. package/lib/utils/ReconnectionMonitor.d.ts +29 -0
  27. package/lib/utils/ReconnectionMonitor.js +72 -0
  28. package/lib/utils/errors/APIError.d.ts +7 -0
  29. package/lib/utils/errors/APIError.js +22 -0
  30. package/lib/utils/errors/assertValidationError.d.ts +5 -0
  31. package/lib/utils/errors/assertValidationError.js +16 -0
  32. package/lib/utils/errors/index.d.ts +3 -0
  33. package/lib/utils/errors/index.js +11 -0
  34. package/lib/utils/errors/validation.d.ts +8 -0
  35. package/lib/utils/errors/validation.js +26 -0
  36. package/lib/utils/index.d.ts +2 -0
  37. package/lib/utils/index.js +8 -0
  38. package/lib/utils/resolveConfig.d.ts +8 -0
  39. package/lib/utils/resolveConfig.js +17 -0
  40. package/lib/utils/resolveCredentials.d.ts +12 -0
  41. package/lib/utils/resolveCredentials.js +22 -0
  42. package/lib-esm/GraphQLAPI.js +0 -5
  43. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +67 -0
  44. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +815 -0
  45. package/lib-esm/Providers/constants.d.ts +95 -0
  46. package/lib-esm/Providers/constants.js +100 -0
  47. package/lib-esm/index.d.ts +0 -3
  48. package/lib-esm/index.js +0 -4
  49. package/lib-esm/internals/InternalGraphQLAPI.d.ts +4 -40
  50. package/lib-esm/internals/InternalGraphQLAPI.js +90 -244
  51. package/lib-esm/internals/index.d.ts +1 -0
  52. package/lib-esm/internals/index.js +1 -1
  53. package/lib-esm/internals/v6.d.ts +89 -0
  54. package/lib-esm/internals/v6.js +96 -0
  55. package/lib-esm/tsconfig.tsbuildinfo +5790 -0
  56. package/lib-esm/types/PubSub.d.ts +27 -0
  57. package/lib-esm/types/PubSub.js +44 -0
  58. package/lib-esm/types/index.d.ts +184 -4
  59. package/lib-esm/types/index.js +0 -3
  60. package/lib-esm/utils/ConnectionStateMonitor.d.ts +41 -0
  61. package/lib-esm/utils/ConnectionStateMonitor.js +141 -0
  62. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +3 -0
  63. package/lib-esm/utils/ReachabilityMonitor/index.js +4 -0
  64. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +3 -0
  65. package/lib-esm/utils/ReachabilityMonitor/index.native.js +7 -0
  66. package/lib-esm/utils/ReconnectionMonitor.d.ts +29 -0
  67. package/lib-esm/utils/ReconnectionMonitor.js +70 -0
  68. package/lib-esm/utils/errors/APIError.d.ts +7 -0
  69. package/lib-esm/utils/errors/APIError.js +20 -0
  70. package/lib-esm/utils/errors/assertValidationError.d.ts +5 -0
  71. package/lib-esm/utils/errors/assertValidationError.js +13 -0
  72. package/lib-esm/utils/errors/index.d.ts +3 -0
  73. package/lib-esm/utils/errors/index.js +5 -0
  74. package/lib-esm/utils/errors/validation.d.ts +8 -0
  75. package/lib-esm/utils/errors/validation.js +24 -0
  76. package/lib-esm/utils/index.d.ts +2 -0
  77. package/lib-esm/utils/index.js +4 -0
  78. package/lib-esm/utils/resolveConfig.d.ts +8 -0
  79. package/lib-esm/utils/resolveConfig.js +15 -0
  80. package/lib-esm/utils/resolveCredentials.d.ts +12 -0
  81. package/lib-esm/utils/resolveCredentials.js +20 -0
  82. package/package.json +114 -114
  83. package/src/GraphQLAPI.ts +0 -2
  84. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +1003 -0
  85. package/src/Providers/constants.ts +110 -0
  86. package/src/index.ts +0 -3
  87. package/src/internals/InternalGraphQLAPI.ts +62 -221
  88. package/src/internals/index.ts +2 -0
  89. package/src/internals/v6.ts +106 -0
  90. package/src/types/PubSub.ts +58 -0
  91. package/src/types/index.ts +234 -7
  92. package/src/utils/ConnectionStateMonitor.ts +195 -0
  93. package/src/utils/ReachabilityMonitor/index.native.ts +7 -0
  94. package/src/utils/ReachabilityMonitor/index.ts +4 -0
  95. package/src/utils/ReconnectionMonitor.ts +76 -0
  96. package/src/utils/errors/APIError.ts +18 -0
  97. package/src/utils/errors/assertValidationError.ts +19 -0
  98. package/src/utils/errors/index.ts +6 -0
  99. package/src/utils/errors/validation.ts +26 -0
  100. package/src/utils/index.ts +5 -0
  101. package/src/utils/resolveConfig.ts +20 -0
  102. package/src/utils/resolveCredentials.ts +14 -0
  103. package/lib/.tsbuildinfo +0 -3
  104. package/lib/GraphQLAPI.js.map +0 -1
  105. package/lib/index.js.map +0 -1
  106. package/lib/internals/InternalGraphQLAPI.js.map +0 -1
  107. package/lib/internals/index.js.map +0 -1
  108. package/lib/types/index.js.map +0 -1
  109. package/lib-esm/.tsbuildinfo +0 -3
  110. package/lib-esm/GraphQLAPI.js.map +0 -1
  111. package/lib-esm/index.js.map +0 -1
  112. package/lib-esm/internals/InternalGraphQLAPI.js.map +0 -1
  113. package/lib-esm/internals/index.js.map +0 -1
  114. 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,5 @@
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;
@@ -9,24 +9,21 @@ import {
9
9
  OperationTypeNode,
10
10
  } from 'graphql';
11
11
  import Observable from 'zen-observable-ts';
12
+ import { Amplify, Cache, fetchAuthSession } from '@aws-amplify/core';
12
13
  import {
13
- Amplify,
14
- ConsoleLogger as Logger,
15
- Credentials,
16
14
  CustomUserAgentDetails,
15
+ ConsoleLogger as Logger,
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
+ } from '@aws-amplify/core/internals/utils';
23
18
  import {
24
19
  GraphQLAuthError,
25
- GraphQLOptions,
26
20
  GraphQLResult,
27
21
  GraphQLOperation,
22
+ GraphQLOptions,
28
23
  } from '../types';
29
- import { RestClient } from '@aws-amplify/api-rest';
24
+ import { post } from '@aws-amplify/api-rest';
25
+ import { AWSAppSyncRealTimeProvider } from '../Providers/AWSAppSyncRealTimeProvider';
26
+
30
27
  const USER_AGENT_HEADER = 'x-amz-user-agent';
31
28
 
32
29
  const logger = new Logger('GraphQLAPI');
@@ -49,11 +46,9 @@ export class InternalGraphQLAPIClass {
49
46
  * @private
50
47
  */
51
48
  private _options;
52
- private _api = null;
49
+ private appSyncRealTime: AWSAppSyncRealTimeProvider | null;
53
50
 
54
- Auth = Auth;
55
51
  Cache = Cache;
56
- Credentials = Credentials;
57
52
 
58
53
  /**
59
54
  * Initialize GraphQL API with AWS configuration
@@ -68,94 +63,41 @@ export class InternalGraphQLAPIClass {
68
63
  return 'InternalGraphQLAPI';
69
64
  }
70
65
 
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
66
  private async _headerBasedAuth(
121
67
  defaultAuthenticationType?,
122
- additionalHeaders: { [key: string]: string } = {}
68
+ additionalHeaders: { [key: string]: string } = {},
69
+ customUserAgentDetails?: CustomUserAgentDetails
123
70
  ) {
124
- const { aws_appsync_authenticationType, aws_appsync_apiKey: apiKey } =
125
- this._options;
126
- const authenticationType =
127
- defaultAuthenticationType || aws_appsync_authenticationType || 'AWS_IAM';
71
+ const config = Amplify.getConfig();
72
+ const {
73
+ region: region,
74
+ endpoint: appSyncGraphqlEndpoint,
75
+ defaultAuthMode: authenticationType,
76
+ } = config.API.AppSync;
77
+
128
78
  let headers = {};
129
79
 
130
- switch (authenticationType) {
131
- case 'API_KEY':
132
- if (!apiKey) {
80
+ switch (authenticationType.type) {
81
+ case 'apiKey':
82
+ if (!authenticationType.apiKey) {
133
83
  throw new Error(GraphQLAuthError.NO_API_KEY);
134
84
  }
135
85
  headers = {
136
- Authorization: null,
137
- 'X-Api-Key': apiKey,
86
+ 'X-Api-Key': authenticationType.apiKey,
138
87
  };
139
88
  break;
140
- case 'AWS_IAM':
141
- const credentialsOK = await this._ensureCredentials();
142
- if (!credentialsOK) {
89
+ case 'iam':
90
+ const session = await fetchAuthSession();
91
+ if (session.credentials === undefined) {
143
92
  throw new Error(GraphQLAuthError.NO_CREDENTIALS);
144
93
  }
145
94
  break;
146
- case 'OPENID_CONNECT':
95
+ case 'jwt':
147
96
  try {
148
97
  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
- }
98
+
99
+ token = (await fetchAuthSession()).tokens?.accessToken.toString();
100
+
159
101
  if (!token) {
160
102
  throw new Error(GraphQLAuthError.NO_FEDERATED_JWT);
161
103
  }
@@ -166,17 +108,7 @@ export class InternalGraphQLAPIClass {
166
108
  throw new Error(GraphQLAuthError.NO_CURRENT_USER);
167
109
  }
168
110
  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':
111
+ case 'custom':
180
112
  if (!additionalHeaders.Authorization) {
181
113
  throw new Error(GraphQLAuthError.NO_AUTH_TOKEN);
182
114
  }
@@ -240,22 +172,11 @@ export class InternalGraphQLAPIClass {
240
172
  switch (operationType) {
241
173
  case 'query':
242
174
  case 'mutation':
243
- this.createInstanceIfNotCreated();
244
- const cancellableToken = this._api.getCancellableToken();
245
- const initParams = {
246
- cancellableToken,
247
- withCredentials: this._options.withCredentials,
248
- };
249
175
  const responsePromise = this._graphql<T>(
250
176
  { query, variables, authMode },
251
177
  headers,
252
- initParams,
253
178
  customUserAgentDetails
254
179
  );
255
- this._api.updateRequestToBeCancellable(
256
- responsePromise,
257
- cancellableToken
258
- );
259
180
  return responsePromise;
260
181
  case 'subscription':
261
182
  return this._graphqlSubscribe(
@@ -271,26 +192,31 @@ export class InternalGraphQLAPIClass {
271
192
  private async _graphql<T = any>(
272
193
  { query, variables, authMode }: GraphQLOptions,
273
194
  additionalHeaders = {},
274
- initParams = {},
275
195
  customUserAgentDetails?: CustomUserAgentDetails
276
196
  ): Promise<GraphQLResult<T>> {
277
- this.createInstanceIfNotCreated();
278
- 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;
197
+ const config = Amplify.getConfig();
198
+
199
+ const { region: region, endpoint: appSyncGraphqlEndpoint } =
200
+ config.API.AppSync;
201
+
202
+ const customGraphqlEndpoint = null;
203
+ const customEndpointRegion = null;
285
204
 
286
205
  const headers = {
287
206
  ...(!customGraphqlEndpoint &&
288
- (await this._headerBasedAuth(authMode, additionalHeaders))),
207
+ (await this._headerBasedAuth(
208
+ authMode,
209
+ additionalHeaders,
210
+ customUserAgentDetails
211
+ ))),
289
212
  ...(customGraphqlEndpoint &&
290
213
  (customEndpointRegion
291
- ? await this._headerBasedAuth(authMode, additionalHeaders)
214
+ ? await this._headerBasedAuth(
215
+ authMode,
216
+ additionalHeaders,
217
+ customUserAgentDetails
218
+ )
292
219
  : { Authorization: null })),
293
- ...(await graphql_headers({ query, variables })),
294
220
  ...additionalHeaders,
295
221
  ...(!customGraphqlEndpoint && {
296
222
  [USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),
@@ -302,18 +228,6 @@ export class InternalGraphQLAPIClass {
302
228
  variables,
303
229
  };
304
230
 
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
- );
316
-
317
231
  const endpoint = customGraphqlEndpoint || appSyncGraphqlEndpoint;
318
232
 
319
233
  if (!endpoint) {
@@ -327,14 +241,13 @@ export class InternalGraphQLAPIClass {
327
241
 
328
242
  let response;
329
243
  try {
330
- response = await this._api.post(endpoint, init);
244
+ response = await post(endpoint, {
245
+ headers,
246
+ body,
247
+ region,
248
+ serviceName: 'appsync',
249
+ });
331
250
  } catch (err) {
332
- // If the exception is because user intentionally
333
- // cancelled the request, do not modify the exception
334
- // so that clients can identify the exception correctly.
335
- if (this._api.isCancel(err)) {
336
- throw err;
337
- }
338
251
  response = {
339
252
  data: {},
340
253
  errors: [new GraphQLError(err.message, null, null, null, null, err)],
@@ -350,39 +263,6 @@ export class InternalGraphQLAPIClass {
350
263
  return response;
351
264
  }
352
265
 
353
- async createInstanceIfNotCreated() {
354
- if (!this._api) {
355
- await this.createInstance();
356
- }
357
- }
358
-
359
- /**
360
- * Checks to see if an error thrown is from an api request cancellation
361
- * @param {any} error - Any error
362
- * @return {boolean} - A boolean indicating if the error was from an api request cancellation
363
- */
364
- isCancel(error) {
365
- return this._api.isCancel(error);
366
- }
367
-
368
- /**
369
- * Cancels an inflight request. Only applicable for graphql queries and mutations
370
- * @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.
381
- */
382
- hasCancelToken(request: Promise<any>) {
383
- return this._api.hasCancelToken(request);
384
- }
385
-
386
266
  private _graphqlSubscribe(
387
267
  {
388
268
  query,
@@ -393,57 +273,18 @@ export class InternalGraphQLAPIClass {
393
273
  additionalHeaders = {},
394
274
  customUserAgentDetails?: CustomUserAgentDetails
395
275
  ): 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');
276
+ const { AppSync } = Amplify.getConfig().API ?? {};
277
+ if (!this.appSyncRealTime) {
278
+ this.appSyncRealTime = new AWSAppSyncRealTimeProvider();
426
279
  }
427
- }
428
-
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
- });
280
+ return this.appSyncRealTime.subscribe({
281
+ query: print(query as DocumentNode),
282
+ variables,
283
+ appSyncGraphqlEndpoint: AppSync.endpoint,
284
+ region: AppSync.region,
285
+ authenticationType: AppSync.defaultAuthMode,
286
+ });
445
287
  }
446
288
  }
447
289
 
448
290
  export const InternalGraphQLAPI = new InternalGraphQLAPIClass(null);
449
- Amplify.register(InternalGraphQLAPI);
@@ -4,3 +4,5 @@ export {
4
4
  InternalGraphQLAPI,
5
5
  InternalGraphQLAPIClass,
6
6
  } from './InternalGraphQLAPI';
7
+
8
+ export { graphql } from './v6';
@@ -0,0 +1,106 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { GraphQLAPI } from '../GraphQLAPI';
4
+ import { GraphQLOptionsV6, GraphQLResponseV6 } from '../types';
5
+
6
+ /**
7
+ * Invokes graphql operations against a graphql service, providing correct input and
8
+ * output types if Amplify-generated graphql from a recent version of the CLI/codegen
9
+ * are used *or* correct typing is provided via the type argument.
10
+ *
11
+ * Amplify-generated "branded" graphql queries will look similar to this:
12
+ *
13
+ * ```ts
14
+ * //
15
+ * // |-- branding
16
+ * // v
17
+ * export const getModel = `...` as GeneratedQuery<
18
+ * GetModelQueryVariables,
19
+ * GetModelQuery
20
+ * >;
21
+ * ```
22
+ *
23
+ * If this branding is not in your generated graphql, update to a newer version of
24
+ * CLI/codegen and regenerate your graphql using `amplify codegen`.
25
+ *
26
+ * ## Using Amplify-generated graphql
27
+ *
28
+ * ```ts
29
+ * import * as queries from './graphql/queries';
30
+ *
31
+ * //
32
+ * // |-- correctly typed graphql response containing a Widget
33
+ * // v
34
+ * const queryResult = await graphql({
35
+ * query: queries.getWidget,
36
+ * variables: {
37
+ * id: "abc", // <-- type hinted/enforced
38
+ * },
39
+ * });
40
+ *
41
+ * //
42
+ * // |-- a correctly typed Widget
43
+ * // v
44
+ * const fetchedWidget = queryResult.data?.getWidget!;
45
+ * ```
46
+ *
47
+ * ## Custom input + result types
48
+ *
49
+ * To provide input types (`variables`) and result types:
50
+ *
51
+ * ```ts
52
+ * type GetById_NameOnly = {
53
+ * variables: {
54
+ * id: string
55
+ * },
56
+ * result: Promise<{
57
+ * data: { getWidget: { name: string } }
58
+ * }>
59
+ * }
60
+ *
61
+ * //
62
+ * // |-- type is GetById_NameOnly["result"]
63
+ * // v
64
+ * const result = graphql<GetById_NameOnly>({
65
+ * query: "...",
66
+ * variables: { id: "abc" } // <-- type of GetById_NameOnly["variables"]
67
+ * });
68
+ * ```
69
+ *
70
+ * ## Custom result type only
71
+ *
72
+ * To specify result types only, use a type that is *not* in the `{variables, result}` shape:
73
+ *
74
+ * ```ts
75
+ * type MyResultType = Promise<{
76
+ * data: {
77
+ * getWidget: { name: string }
78
+ * }
79
+ * }>
80
+ *
81
+ * //
82
+ * // |-- type is MyResultType
83
+ * // v
84
+ * const result = graphql<MyResultType>({query: "..."});
85
+ * ```
86
+ *
87
+ * @param options
88
+ * @param additionalHeaders
89
+ */
90
+ export function graphql<
91
+ FALLBACK_TYPES = unknown,
92
+ TYPED_GQL_STRING extends string = string
93
+ >(
94
+ options: GraphQLOptionsV6<FALLBACK_TYPES, TYPED_GQL_STRING>,
95
+ additionalHeaders?: { [key: string]: string }
96
+ ): GraphQLResponseV6<FALLBACK_TYPES, TYPED_GQL_STRING> {
97
+ /**
98
+ * The correctness of these typings depends on correct string branding or overrides.
99
+ * Neither of these can actually be validated at runtime. Hence, we don't perform
100
+ * any validation or type-guarding here.
101
+ */
102
+ const result = GraphQLAPI.graphql(options, additionalHeaders);
103
+ return result as any;
104
+ }
105
+
106
+ export { GraphQLOptionsV6, GraphQLResponseV6 };
@@ -0,0 +1,58 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { ZenObservable } from 'zen-observable-ts';
4
+
5
+ export interface SubscriptionObserver<T> {
6
+ closed: boolean;
7
+ next(value: T): void;
8
+ error(errorValue: any): void;
9
+ complete(): void;
10
+ }
11
+
12
+ export enum CONTROL_MSG {
13
+ CONNECTION_CLOSED = 'Connection closed',
14
+ CONNECTION_FAILED = 'Connection failed',
15
+ REALTIME_SUBSCRIPTION_INIT_ERROR = 'AppSync Realtime subscription init error',
16
+ SUBSCRIPTION_ACK = 'Subscription ack',
17
+ TIMEOUT_DISCONNECT = 'Timeout disconnect',
18
+ }
19
+
20
+ /** @enum {string} */
21
+ export enum ConnectionState {
22
+ /*
23
+ * The connection is alive and healthy
24
+ */
25
+ Connected = 'Connected',
26
+ /*
27
+ * The connection is alive, but the connection is offline
28
+ */
29
+ ConnectedPendingNetwork = 'ConnectedPendingNetwork',
30
+ /*
31
+ * The connection has been disconnected while in use
32
+ */
33
+ ConnectionDisrupted = 'ConnectionDisrupted',
34
+ /*
35
+ * The connection has been disconnected and the network is offline
36
+ */
37
+ ConnectionDisruptedPendingNetwork = 'ConnectionDisruptedPendingNetwork',
38
+ /*
39
+ * The connection is in the process of connecting
40
+ */
41
+ Connecting = 'Connecting',
42
+ /*
43
+ * The connection is not in use and is being disconnected
44
+ */
45
+ ConnectedPendingDisconnect = 'ConnectedPendingDisconnect',
46
+ /*
47
+ * The connection is not in use and has been disconnected
48
+ */
49
+ Disconnected = 'Disconnected',
50
+ /*
51
+ * The connection is alive, but a keep alive message has been missed
52
+ */
53
+ ConnectedPendingKeepAlive = 'ConnectedPendingKeepAlive',
54
+ }
55
+
56
+ export type PubSubContent = Record<string, unknown> | string;
57
+ export type PubSubContentObserver =
58
+ ZenObservable.SubscriptionObserver<PubSubContent>;