@aws-amplify/api-graphql 4.3.3 → 4.3.4-events.81620c6.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 (92) hide show
  1. package/dist/cjs/GraphQLAPI.js +15 -1
  2. package/dist/cjs/GraphQLAPI.js.map +1 -1
  3. package/dist/cjs/Providers/AWSAppSyncEventsProvider/index.js +88 -0
  4. package/dist/cjs/Providers/AWSAppSyncEventsProvider/index.js.map +1 -0
  5. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js +32 -735
  6. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -1
  7. package/dist/cjs/Providers/AWSWebSocketProvider/appsyncUrl.js +112 -0
  8. package/dist/cjs/Providers/AWSWebSocketProvider/appsyncUrl.js.map +1 -0
  9. package/dist/cjs/Providers/AWSWebSocketProvider/authHeaders.js +99 -0
  10. package/dist/cjs/Providers/AWSWebSocketProvider/authHeaders.js.map +1 -0
  11. package/dist/cjs/Providers/AWSWebSocketProvider/index.js +626 -0
  12. package/dist/cjs/Providers/AWSWebSocketProvider/index.js.map +1 -0
  13. package/dist/cjs/Providers/constants.js +22 -2
  14. package/dist/cjs/Providers/constants.js.map +1 -1
  15. package/dist/cjs/index.js +2 -1
  16. package/dist/cjs/index.js.map +1 -1
  17. package/dist/cjs/internals/InternalGraphQLAPI.js +8 -67
  18. package/dist/cjs/internals/InternalGraphQLAPI.js.map +1 -1
  19. package/dist/cjs/internals/events/appsyncRequest.js +97 -0
  20. package/dist/cjs/internals/events/appsyncRequest.js.map +1 -0
  21. package/dist/cjs/internals/events/index.js +109 -0
  22. package/dist/cjs/internals/events/index.js.map +1 -0
  23. package/dist/cjs/internals/graphqlAuth.js +64 -0
  24. package/dist/cjs/internals/graphqlAuth.js.map +1 -0
  25. package/dist/cjs/internals/graphqlRequest.js +20 -0
  26. package/dist/cjs/internals/graphqlRequest.js.map +1 -0
  27. package/dist/cjs/utils/ReconnectionMonitor.js +1 -1
  28. package/dist/cjs/utils/ReconnectionMonitor.js.map +1 -1
  29. package/dist/cjs/utils/resolveConfig.js +18 -1
  30. package/dist/cjs/utils/resolveConfig.js.map +1 -1
  31. package/dist/esm/GraphQLAPI.mjs +15 -1
  32. package/dist/esm/GraphQLAPI.mjs.map +1 -1
  33. package/dist/esm/Providers/AWSAppSyncEventsProvider/index.d.ts +37 -0
  34. package/dist/esm/Providers/AWSAppSyncEventsProvider/index.mjs +86 -0
  35. package/dist/esm/Providers/AWSAppSyncEventsProvider/index.mjs.map +1 -0
  36. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +20 -71
  37. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs +32 -735
  38. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs.map +1 -1
  39. package/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.d.ts +21 -0
  40. package/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.mjs +106 -0
  41. package/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.mjs.map +1 -0
  42. package/dist/esm/Providers/AWSWebSocketProvider/authHeaders.d.ts +8 -0
  43. package/dist/esm/Providers/AWSWebSocketProvider/authHeaders.mjs +97 -0
  44. package/dist/esm/Providers/AWSWebSocketProvider/authHeaders.mjs.map +1 -0
  45. package/dist/esm/Providers/AWSWebSocketProvider/index.d.ts +79 -0
  46. package/dist/esm/Providers/AWSWebSocketProvider/index.mjs +624 -0
  47. package/dist/esm/Providers/AWSWebSocketProvider/index.mjs.map +1 -0
  48. package/dist/esm/Providers/constants.d.ts +23 -3
  49. package/dist/esm/Providers/constants.mjs +22 -2
  50. package/dist/esm/Providers/constants.mjs.map +1 -1
  51. package/dist/esm/index.d.ts +1 -0
  52. package/dist/esm/index.mjs +2 -0
  53. package/dist/esm/index.mjs.map +1 -1
  54. package/dist/esm/internals/InternalGraphQLAPI.d.ts +0 -1
  55. package/dist/esm/internals/InternalGraphQLAPI.mjs +9 -68
  56. package/dist/esm/internals/InternalGraphQLAPI.mjs.map +1 -1
  57. package/dist/esm/internals/events/appsyncRequest.d.ts +14 -0
  58. package/dist/esm/internals/events/appsyncRequest.mjs +96 -0
  59. package/dist/esm/internals/events/appsyncRequest.mjs.map +1 -0
  60. package/dist/esm/internals/events/index.d.ts +31 -0
  61. package/dist/esm/internals/events/index.mjs +105 -0
  62. package/dist/esm/internals/events/index.mjs.map +1 -0
  63. package/dist/esm/internals/graphqlAuth.d.ts +3 -0
  64. package/dist/esm/internals/graphqlAuth.mjs +64 -0
  65. package/dist/esm/internals/graphqlAuth.mjs.map +1 -0
  66. package/dist/esm/internals/graphqlRequest.d.ts +3 -0
  67. package/dist/esm/internals/graphqlRequest.mjs +18 -0
  68. package/dist/esm/internals/graphqlRequest.mjs.map +1 -0
  69. package/dist/esm/utils/ConnectionStateMonitor.d.ts +29 -1
  70. package/dist/esm/utils/ReconnectionMonitor.d.ts +1 -1
  71. package/dist/esm/utils/ReconnectionMonitor.mjs +1 -1
  72. package/dist/esm/utils/ReconnectionMonitor.mjs.map +1 -1
  73. package/dist/esm/utils/resolveConfig.d.ts +9 -0
  74. package/dist/esm/utils/resolveConfig.mjs +17 -1
  75. package/dist/esm/utils/resolveConfig.mjs.map +1 -1
  76. package/package.json +5 -5
  77. package/src/GraphQLAPI.ts +34 -3
  78. package/src/Providers/AWSAppSyncEventsProvider/index.ts +174 -0
  79. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +52 -1055
  80. package/src/Providers/AWSWebSocketProvider/appsyncUrl.ts +151 -0
  81. package/src/Providers/AWSWebSocketProvider/authHeaders.ts +146 -0
  82. package/src/Providers/AWSWebSocketProvider/index.ts +923 -0
  83. package/src/Providers/constants.ts +22 -2
  84. package/src/index.ts +1 -0
  85. package/src/internals/InternalGraphQLAPI.ts +15 -102
  86. package/src/internals/events/appsyncRequest.ts +173 -0
  87. package/src/internals/events/index.ts +209 -0
  88. package/src/internals/graphqlAuth.ts +87 -0
  89. package/src/internals/graphqlRequest.ts +30 -0
  90. package/src/utils/ConnectionStateMonitor.ts +2 -13
  91. package/src/utils/ReconnectionMonitor.ts +1 -1
  92. package/src/utils/resolveConfig.ts +23 -0
@@ -36,9 +36,9 @@ export enum MESSAGE_TYPES {
36
36
  GQL_START_ACK = 'start_ack',
37
37
  /**
38
38
  * Server -> Client message.
39
- * This message type is for subscription message from AWS AppSync RealTime
39
+ * This message type is for subscription message from AWS AppSync RealTime or Events
40
40
  */
41
- GQL_DATA = 'data',
41
+ DATA = 'data',
42
42
  /**
43
43
  * Server -> Client message.
44
44
  * This message type helps the client to know is still receiving messages from AWS AppSync RealTime
@@ -59,6 +59,26 @@ export enum MESSAGE_TYPES {
59
59
  * This message type is for sending error messages from AWS AppSync RealTime to the client
60
60
  */
61
61
  GQL_ERROR = 'error', // Server -> Client
62
+ /**
63
+ * Client -> Server message.
64
+ * This message type is for registering subscriptions with Events
65
+ */
66
+ EVENT_SUBSCRIBE = 'subscribe',
67
+ /**
68
+ * Client -> Server message.
69
+ * This message type is for publishing a message with Events
70
+ */
71
+ EVENT_PUBLISH = 'publish',
72
+ /**
73
+ * Server -> Client message.
74
+ * Server acknowledges successful subscription
75
+ */
76
+ EVENT_SUBSCRIBE_ACK = 'subscribe_success',
77
+ /**
78
+ * Server -> Client message.
79
+ * Server acknowledges successful publish
80
+ */
81
+ EVENT_PUBLISH_ACK = 'publish_success',
62
82
  }
63
83
 
64
84
  export enum SUBSCRIPTION_STATUS {
package/src/index.ts CHANGED
@@ -5,3 +5,4 @@ export { GraphQLAPI, GraphQLAPIClass, graphqlOperation } from './GraphQLAPI';
5
5
  export * from './types';
6
6
 
7
7
  export { CONNECTION_STATE_CHANGE } from './Providers/constants';
8
+ export * as events from './internals/events';
@@ -12,7 +12,6 @@ import { AmplifyClassV6 } from '@aws-amplify/core';
12
12
  import {
13
13
  AmplifyUrl,
14
14
  CustomUserAgentDetails,
15
- GraphQLAuthMode,
16
15
  getAmplifyUserAgent,
17
16
  } from '@aws-amplify/core/internals/utils';
18
17
  import { isCancelError as isCancelErrorREST } from '@aws-amplify/api-rest';
@@ -30,17 +29,11 @@ import { AWSAppSyncRealTimeProvider } from '../Providers/AWSAppSyncRealTimeProvi
30
29
  import { GraphQLOperation, GraphQLOptions, GraphQLResult } from '../types';
31
30
  import { resolveConfig, resolveLibraryOptions } from '../utils';
32
31
  import { repackageUnauthorizedError } from '../utils/errors/repackageAuthError';
33
- import {
34
- NO_API_KEY,
35
- NO_AUTH_TOKEN_HEADER,
36
- NO_ENDPOINT,
37
- NO_SIGNED_IN_USER,
38
- NO_VALID_AUTH_TOKEN,
39
- NO_VALID_CREDENTIALS,
40
- } from '../utils/errors/constants';
32
+ import { NO_ENDPOINT } from '../utils/errors/constants';
41
33
  import { GraphQLApiError, createGraphQLResultWithError } from '../utils/errors';
42
34
 
43
35
  import { isGraphQLResponseWithErrors } from './utils/runtimeTypeGuards/isGraphQLResponseWithErrors';
36
+ import { headerBasedAuth } from './graphqlAuth';
44
37
 
45
38
  const USER_AGENT_HEADER = 'x-amz-user-agent';
46
39
 
@@ -72,80 +65,6 @@ export class InternalGraphQLAPIClass {
72
65
  return 'InternalGraphQLAPI';
73
66
  }
74
67
 
75
- private async _headerBasedAuth(
76
- amplify: AmplifyClassV6,
77
- authMode: GraphQLAuthMode,
78
- additionalHeaders: Record<string, string> = {},
79
- ) {
80
- const { apiKey } = resolveConfig(amplify);
81
-
82
- let headers = {};
83
-
84
- switch (authMode) {
85
- case 'apiKey':
86
- if (!apiKey) {
87
- throw new GraphQLApiError(NO_API_KEY);
88
- }
89
- headers = {
90
- 'X-Api-Key': apiKey,
91
- };
92
- break;
93
- case 'iam': {
94
- const session = await amplify.Auth.fetchAuthSession();
95
- if (session.credentials === undefined) {
96
- throw new GraphQLApiError(NO_VALID_CREDENTIALS);
97
- }
98
- break;
99
- }
100
- case 'oidc':
101
- case 'userPool': {
102
- let token: string | undefined;
103
-
104
- try {
105
- token = (
106
- await amplify.Auth.fetchAuthSession()
107
- ).tokens?.accessToken.toString();
108
- } catch (e) {
109
- // fetchAuthSession failed
110
- throw new GraphQLApiError({
111
- ...NO_SIGNED_IN_USER,
112
- underlyingError: e,
113
- });
114
- }
115
-
116
- // `fetchAuthSession()` succeeded but didn't return `tokens`.
117
- // This may happen when unauthenticated access is enabled and there is
118
- // no user signed in.
119
- if (!token) {
120
- throw new GraphQLApiError(NO_VALID_AUTH_TOKEN);
121
- }
122
-
123
- headers = {
124
- Authorization: token,
125
- };
126
- break;
127
- }
128
- case 'lambda':
129
- if (
130
- typeof additionalHeaders === 'object' &&
131
- !additionalHeaders.Authorization
132
- ) {
133
- throw new GraphQLApiError(NO_AUTH_TOKEN_HEADER);
134
- }
135
-
136
- headers = {
137
- Authorization: additionalHeaders.Authorization,
138
- };
139
- break;
140
- case 'none':
141
- break;
142
- default:
143
- break;
144
- }
145
-
146
- return headers;
147
- }
148
-
149
68
  /**
150
69
  * to get the operation type
151
70
  * @param operation
@@ -252,6 +171,7 @@ export class InternalGraphQLAPIClass {
252
171
  authToken?: string,
253
172
  ): Promise<GraphQLResult<T>> {
254
173
  const {
174
+ apiKey,
255
175
  region,
256
176
  endpoint: appSyncGraphqlEndpoint,
257
177
  customEndpoint,
@@ -303,29 +223,22 @@ export class InternalGraphQLAPIClass {
303
223
  };
304
224
  }
305
225
 
306
- // TODO: Figure what we need to do to remove `!`'s.
226
+ const authHeaders = await headerBasedAuth(
227
+ amplify,
228
+ authMode,
229
+ apiKey,
230
+ additionalCustomHeaders,
231
+ );
232
+
307
233
  const headers = {
308
- ...(!customEndpoint &&
309
- (await this._headerBasedAuth(
310
- amplify,
311
- authMode!,
312
- additionalCustomHeaders,
313
- ))),
234
+ ...(!customEndpoint && authHeaders),
314
235
  /**
315
236
  * Custom endpoint headers.
316
237
  * If there is both a custom endpoint and custom region present, we get the headers.
317
238
  * If there is a custom endpoint but no region, we return an empty object.
318
239
  * If neither are present, we return an empty object.
319
240
  */
320
- ...((customEndpoint &&
321
- (customEndpointRegion
322
- ? await this._headerBasedAuth(
323
- amplify,
324
- authMode!,
325
- additionalCustomHeaders,
326
- )
327
- : {})) ||
328
- {}),
241
+ ...((customEndpoint && (customEndpointRegion ? authHeaders : {})) || {}),
329
242
  // Custom headers included in Amplify configuration options:
330
243
  ...(customHeaders &&
331
244
  (await customHeaders({
@@ -378,9 +291,9 @@ export class InternalGraphQLAPIClass {
378
291
  let response: any;
379
292
 
380
293
  try {
381
- // See the inline doc of the REST `post()` API for possible errors to be thrown.
382
- // As these errors are catastrophic they should be caught and handled by GraphQL
383
- // API consumers.
294
+ // // // See the inline doc of the REST `post()` API for possible errors to be thrown.
295
+ // // // As these errors are catastrophic they should be caught and handled by GraphQL
296
+ // // // API consumers.
384
297
  const { body: responseBody } = await this._api.post(amplify, {
385
298
  url: new AmplifyUrl(endpoint),
386
299
  options: {
@@ -0,0 +1,173 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { AmplifyClassV6 } from '@aws-amplify/core';
4
+ import {
5
+ AmplifyUrl,
6
+ CustomUserAgentDetails,
7
+ GraphQLAuthMode,
8
+ getAmplifyUserAgent,
9
+ } from '@aws-amplify/core/internals/utils';
10
+ import {
11
+ // cancel as cancelREST,
12
+ post,
13
+ // updateRequestToBeCancellable,
14
+ } from '@aws-amplify/api-rest/internals';
15
+ import {
16
+ CustomHeaders,
17
+ RequestOptions,
18
+ } from '@aws-amplify/data-schema/runtime';
19
+
20
+ import { resolveLibraryOptions } from '../../utils';
21
+ import { repackageUnauthorizedError } from '../../utils/errors/repackageAuthError';
22
+ import { headerBasedAuth } from '../graphqlAuth';
23
+ import { isGraphQLResponseWithErrors } from '../utils/runtimeTypeGuards/isGraphQLResponseWithErrors';
24
+
25
+ const USER_AGENT_HEADER = 'x-amz-user-agent';
26
+
27
+ interface GqlRequestOptions {
28
+ apiKey: string | undefined;
29
+ region: string;
30
+ appSyncGraphqlEndpoint: string;
31
+ authenticationType: GraphQLAuthMode;
32
+ query: string;
33
+ variables: string[];
34
+ authToken?: string;
35
+ }
36
+
37
+ // This is effectively a copy of InternalGraphQLAPI.ts._graphql(...)
38
+ // Our existing unit tests are tightly coupled to the implementation, so i was unable to refactor
39
+ // and extend _graphql() without having to change a bunch of tests as well... which in turn reduces confidence
40
+ // that this feature will _not affect_ GQL behavior.
41
+ export async function appsyncRequest<T = any>(
42
+ amplify: AmplifyClassV6,
43
+ options: GqlRequestOptions,
44
+ additionalHeaders: CustomHeaders = {},
45
+ abortController: AbortController,
46
+ customUserAgentDetails?: CustomUserAgentDetails,
47
+ ): Promise<T> {
48
+ const {
49
+ region,
50
+ appSyncGraphqlEndpoint: endpoint,
51
+ authenticationType: authMode,
52
+ query,
53
+ variables,
54
+ } = options;
55
+
56
+ if (!endpoint) {
57
+ throw new Error('No endpoint');
58
+ }
59
+
60
+ const { withCredentials } = resolveLibraryOptions(amplify);
61
+
62
+ const headers = await requestHeaders(
63
+ amplify,
64
+ options,
65
+ additionalHeaders,
66
+ customUserAgentDetails,
67
+ );
68
+
69
+ const body = {
70
+ channel: query as string,
71
+ events: variables,
72
+ };
73
+
74
+ const signingServiceInfo = ['apiKey', 'none'].includes(authMode)
75
+ ? undefined
76
+ : {
77
+ service: 'appsync',
78
+ region,
79
+ };
80
+
81
+ const { body: responseBody } = await post(amplify, {
82
+ url: new AmplifyUrl(endpoint),
83
+ options: {
84
+ headers,
85
+ body,
86
+ signingServiceInfo,
87
+ withCredentials,
88
+ },
89
+ abortController,
90
+ });
91
+
92
+ const response = await responseBody.json();
93
+
94
+ if (isGraphQLResponseWithErrors(response)) {
95
+ throw repackageUnauthorizedError(response);
96
+ }
97
+
98
+ return response as T;
99
+ }
100
+
101
+ /**
102
+ * Computes all the necessary HTTP headers for the request based on:
103
+ * 1. Operation-level header options
104
+ * 2. Amplify.configure custom headers
105
+ * 3. AuthZ headers for explicit auth mode specified for operation ?? default auth mode in config
106
+ *
107
+ * @returns HTTP request headers key/value
108
+ */
109
+ async function requestHeaders(
110
+ amplify: AmplifyClassV6,
111
+ options: GqlRequestOptions,
112
+ additionalHeaders: CustomHeaders,
113
+ customUserAgentDetails?: CustomUserAgentDetails,
114
+ ) {
115
+ const {
116
+ apiKey,
117
+ appSyncGraphqlEndpoint: endpoint,
118
+ authenticationType: authMode,
119
+ query,
120
+ variables,
121
+ authToken,
122
+ } = options;
123
+
124
+ const { headers: customHeadersFn } = resolveLibraryOptions(amplify);
125
+
126
+ let additionalCustomHeaders: Record<string, string>;
127
+
128
+ if (typeof additionalHeaders === 'function') {
129
+ const requestOptions: RequestOptions = {
130
+ method: 'POST',
131
+ url: new AmplifyUrl(endpoint).toString(),
132
+ queryString: query,
133
+ };
134
+
135
+ additionalCustomHeaders = await additionalHeaders(requestOptions);
136
+ } else {
137
+ additionalCustomHeaders = additionalHeaders;
138
+ }
139
+
140
+ // if an authorization header is set, have the operation-level authToken take precedence
141
+ if (authToken) {
142
+ additionalCustomHeaders = {
143
+ ...additionalCustomHeaders,
144
+ Authorization: authToken,
145
+ };
146
+ }
147
+
148
+ const authHeaders = await headerBasedAuth(
149
+ amplify,
150
+ authMode,
151
+ apiKey,
152
+ additionalCustomHeaders,
153
+ );
154
+
155
+ const customHeaders =
156
+ customHeadersFn &&
157
+ (await customHeadersFn({
158
+ query,
159
+ variables: variables as any,
160
+ }));
161
+
162
+ const headers = {
163
+ ...authHeaders,
164
+ // Custom headers included in Amplify configuration options:
165
+ ...customHeaders,
166
+ // Custom headers from individual requests or API client configuration:
167
+ ...additionalCustomHeaders,
168
+ // User agent headers:
169
+ [USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),
170
+ };
171
+
172
+ return headers;
173
+ }
@@ -0,0 +1,209 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { Observable } from 'rxjs';
5
+ import { Amplify } from '@aws-amplify/core';
6
+ import {
7
+ DocumentType,
8
+ GraphQLAuthMode,
9
+ } from '@aws-amplify/core/internals/utils';
10
+
11
+ import { AWSAppSyncEventProvider } from '../../Providers/AWSAppSyncEventsProvider';
12
+
13
+ import { appsyncRequest } from './appsyncRequest';
14
+
15
+ type ResolvedGraphQLAuthModes = Exclude<GraphQLAuthMode, 'identityPool'>;
16
+ interface EventsOptions {
17
+ authMode?: GraphQLAuthMode;
18
+ authToken?: string;
19
+ }
20
+
21
+ const eventProvider = new AWSAppSyncEventProvider();
22
+
23
+ const normalizeAuth = (
24
+ explicitAuthMode: GraphQLAuthMode | undefined,
25
+ defaultAuthMode: ResolvedGraphQLAuthModes,
26
+ ): ResolvedGraphQLAuthModes => {
27
+ if (!explicitAuthMode) {
28
+ return defaultAuthMode;
29
+ }
30
+
31
+ if (explicitAuthMode === 'identityPool') {
32
+ return 'iam';
33
+ }
34
+
35
+ return explicitAuthMode;
36
+ };
37
+
38
+ const configure = () => {
39
+ const config = Amplify.getConfig() as any;
40
+
41
+ // TODO - get this correct
42
+ const eventsConfig = config.API?.GraphQL?.events ?? config.data?.events;
43
+
44
+ if (!eventsConfig) {
45
+ throw new Error(
46
+ 'Amplify configuration is missing. Have you called Amplify.configure()',
47
+ );
48
+ }
49
+
50
+ const configAuthMode = normalizeAuth(
51
+ eventsConfig.defaultAuthMode ?? eventsConfig.default_authorization_type,
52
+ 'apiKey',
53
+ );
54
+
55
+ const options = {
56
+ appSyncGraphqlEndpoint: eventsConfig.url,
57
+ region: eventsConfig.region ?? eventsConfig.aws_region,
58
+ authenticationType: configAuthMode,
59
+ apiKey: eventsConfig.apiKey ?? eventsConfig.api_key,
60
+ };
61
+
62
+ return options;
63
+ };
64
+
65
+ interface SubscriptionObserver<T> {
66
+ next(value: T): void;
67
+ error(errorValue: any): void;
68
+ }
69
+
70
+ /**
71
+ *
72
+ * @param channelName
73
+ * @param options
74
+ */
75
+ async function connect(channelName: string, options?: EventsOptions) {
76
+ const providerOptions = configure();
77
+
78
+ providerOptions.authenticationType = normalizeAuth(
79
+ options?.authMode,
80
+ providerOptions.authenticationType,
81
+ );
82
+
83
+ await eventProvider.connect(providerOptions);
84
+
85
+ const sub = (
86
+ observer: SubscriptionObserver<any>,
87
+ subOptions?: EventsOptions,
88
+ ): Observable<any> => {
89
+ const subscribeOptions = { ...providerOptions, query: channelName };
90
+ subscribeOptions.authenticationType = normalizeAuth(
91
+ subOptions?.authMode,
92
+ subscribeOptions.authenticationType,
93
+ );
94
+
95
+ const _sub = eventProvider.subscribe(subscribeOptions);
96
+ _sub.subscribe(observer);
97
+
98
+ return _sub;
99
+ };
100
+
101
+ // WS publish is not enabled in the service yet. It will be a follow up feature
102
+ const _pub = async (
103
+ event: DocumentType,
104
+ pubOptions?: EventsOptions,
105
+ ): Promise<any> => {
106
+ const publishOptions = {
107
+ ...providerOptions,
108
+ query: channelName,
109
+ variables: event,
110
+ };
111
+ publishOptions.authenticationType = normalizeAuth(
112
+ pubOptions?.authMode,
113
+ publishOptions.authenticationType,
114
+ );
115
+
116
+ return eventProvider.publish(publishOptions);
117
+ };
118
+
119
+ return {
120
+ // WS publish is not enabled in the service yet, will be a follow up feature
121
+ // publish: pub,
122
+ subscribe: sub,
123
+ };
124
+ }
125
+
126
+ interface PublishedEvent {
127
+ identifier: string;
128
+ index: number;
129
+ }
130
+ interface PublishResponse {
131
+ failed: PublishedEvent[];
132
+ successful: PublishedEvent[];
133
+ }
134
+
135
+ /**
136
+ * Event API expects and array of JSON strings
137
+ *
138
+ * @param events - JSON-serializable value or an array of values
139
+ * @returns array of JSON strings
140
+ */
141
+ const serializeEvents = (events: DocumentType | DocumentType[]): string[] => {
142
+ if (Array.isArray(events)) {
143
+ return events.map((ev, idx) => {
144
+ const eventJson = JSON.stringify(ev);
145
+ if (eventJson === undefined) {
146
+ throw new Error(
147
+ `Event must be a valid JSON value. Received ${ev} at index ${idx}`,
148
+ );
149
+ }
150
+
151
+ return eventJson;
152
+ });
153
+ }
154
+
155
+ const eventJson = JSON.stringify(events);
156
+ if (eventJson === undefined) {
157
+ throw new Error(`Event must be a valid JSON value. Received ${events}`);
158
+ }
159
+
160
+ return [eventJson];
161
+ };
162
+
163
+ /**
164
+ *
165
+ * @param channelName - publish destination
166
+ * @param event - JSON-serializable value or an array of values
167
+ * @param options
168
+ */
169
+ async function post(
170
+ channelName: string,
171
+ event: DocumentType | DocumentType[],
172
+ options?: EventsOptions,
173
+ ): Promise<void | PublishedEvent[]> {
174
+ const providerOptions = configure();
175
+ providerOptions.authenticationType = normalizeAuth(
176
+ options?.authMode,
177
+ providerOptions.authenticationType,
178
+ );
179
+
180
+ // trailing slash required in publish
181
+ const normalizedChannelName =
182
+ channelName[0] === '/' ? channelName : `/${channelName}`;
183
+
184
+ const publishOptions = {
185
+ ...providerOptions,
186
+ query: normalizedChannelName,
187
+ variables: serializeEvents(event),
188
+ authToken: options?.authToken,
189
+ };
190
+
191
+ const abortController = new AbortController();
192
+
193
+ const res = await appsyncRequest<PublishResponse>(
194
+ Amplify,
195
+ publishOptions,
196
+ {},
197
+ abortController,
198
+ );
199
+
200
+ if (res.failed?.length > 0) {
201
+ return res.failed;
202
+ }
203
+ }
204
+
205
+ function closeAll(): void {
206
+ eventProvider.close();
207
+ }
208
+
209
+ export { connect, post, closeAll };
@@ -0,0 +1,87 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { GraphQLAuthMode } from '@aws-amplify/core/internals/utils';
5
+ import { AmplifyClassV6 } from '@aws-amplify/core';
6
+
7
+ import { GraphQLApiError } from '../utils/errors';
8
+ import {
9
+ NO_API_KEY,
10
+ NO_AUTH_TOKEN_HEADER,
11
+ NO_SIGNED_IN_USER,
12
+ NO_VALID_AUTH_TOKEN,
13
+ NO_VALID_CREDENTIALS,
14
+ } from '../utils/errors/constants';
15
+
16
+ export async function headerBasedAuth(
17
+ amplify: AmplifyClassV6,
18
+ authMode: GraphQLAuthMode,
19
+ apiKey: string | undefined,
20
+ additionalHeaders: Record<string, string> = {},
21
+ ) {
22
+ let headers = {};
23
+
24
+ switch (authMode) {
25
+ case 'apiKey':
26
+ if (!apiKey) {
27
+ throw new GraphQLApiError(NO_API_KEY);
28
+ }
29
+ headers = {
30
+ 'X-Api-Key': apiKey,
31
+ };
32
+ break;
33
+ case 'iam': {
34
+ const session = await amplify.Auth.fetchAuthSession();
35
+ if (session.credentials === undefined) {
36
+ throw new GraphQLApiError(NO_VALID_CREDENTIALS);
37
+ }
38
+ break;
39
+ }
40
+ case 'oidc':
41
+ case 'userPool': {
42
+ let token: string | undefined;
43
+
44
+ try {
45
+ token = (
46
+ await amplify.Auth.fetchAuthSession()
47
+ ).tokens?.accessToken.toString();
48
+ } catch (e) {
49
+ // fetchAuthSession failed
50
+ throw new GraphQLApiError({
51
+ ...NO_SIGNED_IN_USER,
52
+ underlyingError: e,
53
+ });
54
+ }
55
+
56
+ // `fetchAuthSession()` succeeded but didn't return `tokens`.
57
+ // This may happen when unauthenticated access is enabled and there is
58
+ // no user signed in.
59
+ if (!token) {
60
+ throw new GraphQLApiError(NO_VALID_AUTH_TOKEN);
61
+ }
62
+
63
+ headers = {
64
+ Authorization: token,
65
+ };
66
+ break;
67
+ }
68
+ case 'lambda':
69
+ if (
70
+ typeof additionalHeaders === 'object' &&
71
+ !additionalHeaders.Authorization
72
+ ) {
73
+ throw new GraphQLApiError(NO_AUTH_TOKEN_HEADER);
74
+ }
75
+
76
+ headers = {
77
+ Authorization: additionalHeaders.Authorization,
78
+ };
79
+ break;
80
+ case 'none':
81
+ break;
82
+ default:
83
+ break;
84
+ }
85
+
86
+ return headers;
87
+ }
@@ -0,0 +1,30 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { AmplifyUrl } from '@aws-amplify/core/internals/utils';
5
+ import { AmplifyClassV6 } from '@aws-amplify/core';
6
+ import {
7
+ // cancel as cancelREST,
8
+ post,
9
+ // updateRequestToBeCancellable,
10
+ } from '@aws-amplify/api-rest/internals';
11
+
12
+ export async function graphqlRequest(
13
+ amplify: AmplifyClassV6,
14
+ url: string,
15
+ options: any,
16
+ abortController: AbortController,
17
+ _post?: typeof post,
18
+ ) {
19
+ const p = _post ?? post;
20
+
21
+ const { body: responseBody } = await p(amplify, {
22
+ url: new AmplifyUrl(url),
23
+ options,
24
+ abortController,
25
+ });
26
+
27
+ const response = await responseBody.json();
28
+
29
+ return response;
30
+ }