@aws-amplify/api-graphql 4.0.21 → 4.0.22-unstable.1820354.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 (106) hide show
  1. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js +40 -31
  2. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -1
  3. package/dist/cjs/internals/APIClient.js +34 -19
  4. package/dist/cjs/internals/APIClient.js.map +1 -1
  5. package/dist/cjs/internals/InternalGraphQLAPI.js +10 -9
  6. package/dist/cjs/internals/InternalGraphQLAPI.js.map +1 -1
  7. package/dist/cjs/internals/generateClient.js +4 -1
  8. package/dist/cjs/internals/generateClient.js.map +1 -1
  9. package/dist/cjs/internals/generateCustomOperationsProperty.js +6 -1
  10. package/dist/cjs/internals/generateCustomOperationsProperty.js.map +1 -1
  11. package/dist/cjs/internals/operations/custom.js +90 -7
  12. package/dist/cjs/internals/operations/custom.js.map +1 -1
  13. package/dist/cjs/internals/operations/list.js +1 -1
  14. package/dist/cjs/internals/operations/list.js.map +1 -1
  15. package/dist/cjs/internals/server/generateClientWithAmplifyInstance.js +1 -1
  16. package/dist/cjs/internals/server/generateClientWithAmplifyInstance.js.map +1 -1
  17. package/dist/cjs/internals/server/generateModelsProperty.js +1 -1
  18. package/dist/cjs/internals/server/generateModelsProperty.js.map +1 -1
  19. package/dist/cjs/internals/v6.js +0 -2
  20. package/dist/cjs/internals/v6.js.map +1 -1
  21. package/dist/cjs/utils/errors/repackageAuthError.js +1 -1
  22. package/dist/cjs/utils/errors/repackageAuthError.js.map +1 -1
  23. package/dist/cjs/utils/resolveOwnerFields.js +3 -0
  24. package/dist/cjs/utils/resolveOwnerFields.js.map +1 -1
  25. package/dist/esm/GraphQLAPI.d.ts +2 -2
  26. package/dist/esm/GraphQLAPI.mjs.map +1 -1
  27. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +8 -8
  28. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs +40 -31
  29. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs.map +1 -1
  30. package/dist/esm/internals/APIClient.d.ts +5 -6
  31. package/dist/esm/internals/APIClient.mjs +34 -19
  32. package/dist/esm/internals/APIClient.mjs.map +1 -1
  33. package/dist/esm/internals/InternalGraphQLAPI.d.ts +1 -1
  34. package/dist/esm/internals/InternalGraphQLAPI.mjs +10 -9
  35. package/dist/esm/internals/InternalGraphQLAPI.mjs.map +1 -1
  36. package/dist/esm/internals/generateClient.mjs +5 -2
  37. package/dist/esm/internals/generateClient.mjs.map +1 -1
  38. package/dist/esm/internals/generateCustomOperationsProperty.d.ts +4 -3
  39. package/dist/esm/internals/generateCustomOperationsProperty.mjs +5 -1
  40. package/dist/esm/internals/generateCustomOperationsProperty.mjs.map +1 -1
  41. package/dist/esm/internals/operations/custom.d.ts +6 -3
  42. package/dist/esm/internals/operations/custom.mjs +90 -7
  43. package/dist/esm/internals/operations/custom.mjs.map +1 -1
  44. package/dist/esm/internals/operations/get.d.ts +1 -1
  45. package/dist/esm/internals/operations/get.mjs.map +1 -1
  46. package/dist/esm/internals/operations/indexQuery.d.ts +3 -3
  47. package/dist/esm/internals/operations/indexQuery.mjs.map +1 -1
  48. package/dist/esm/internals/operations/list.d.ts +1 -1
  49. package/dist/esm/internals/operations/list.mjs +1 -1
  50. package/dist/esm/internals/operations/list.mjs.map +1 -1
  51. package/dist/esm/internals/operations/subscription.d.ts +1 -1
  52. package/dist/esm/internals/operations/subscription.mjs.map +1 -1
  53. package/dist/esm/internals/server/generateClientWithAmplifyInstance.d.ts +1 -1
  54. package/dist/esm/internals/server/generateClientWithAmplifyInstance.mjs +1 -1
  55. package/dist/esm/internals/server/generateClientWithAmplifyInstance.mjs.map +1 -1
  56. package/dist/esm/internals/server/generateModelsProperty.d.ts +3 -3
  57. package/dist/esm/internals/server/generateModelsProperty.mjs +1 -1
  58. package/dist/esm/internals/server/generateModelsProperty.mjs.map +1 -1
  59. package/dist/esm/internals/types.d.ts +2 -2
  60. package/dist/esm/internals/utils/clientProperties/generateModelsProperty.d.ts +2 -2
  61. package/dist/esm/internals/v6.d.ts +1 -1
  62. package/dist/esm/internals/v6.mjs +0 -2
  63. package/dist/esm/internals/v6.mjs.map +1 -1
  64. package/dist/esm/types/index.d.ts +34 -35
  65. package/dist/esm/utils/ConnectionStateMonitor.d.ts +2 -2
  66. package/dist/esm/utils/ConnectionStateMonitor.mjs.map +1 -1
  67. package/dist/esm/utils/ReachabilityMonitor/index.native.mjs.map +1 -1
  68. package/dist/esm/utils/errors/repackageAuthError.d.ts +2 -2
  69. package/dist/esm/utils/errors/repackageAuthError.mjs +1 -1
  70. package/dist/esm/utils/errors/repackageAuthError.mjs.map +1 -1
  71. package/dist/esm/utils/findIndexByFields.d.ts +1 -1
  72. package/dist/esm/utils/resolveOwnerFields.mjs +3 -0
  73. package/dist/esm/utils/resolveOwnerFields.mjs.map +1 -1
  74. package/package.json +8 -7
  75. package/src/GraphQLAPI.ts +4 -3
  76. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +84 -64
  77. package/src/internals/APIClient.ts +83 -58
  78. package/src/internals/InternalGraphQLAPI.ts +26 -30
  79. package/src/internals/clientUtils.ts +1 -1
  80. package/src/internals/generateClient.ts +23 -10
  81. package/src/internals/generateCustomOperationsProperty.ts +31 -8
  82. package/src/internals/operations/custom.ts +159 -32
  83. package/src/internals/operations/get.ts +9 -8
  84. package/src/internals/operations/indexQuery.ts +12 -11
  85. package/src/internals/operations/list.ts +11 -15
  86. package/src/internals/operations/observeQuery.ts +3 -1
  87. package/src/internals/operations/subscription.ts +12 -10
  88. package/src/internals/server/generateClientWithAmplifyInstance.ts +7 -7
  89. package/src/internals/server/generateModelsProperty.ts +12 -6
  90. package/src/internals/types.ts +2 -2
  91. package/src/internals/utils/clientProperties/generateEnumsProperty.ts +7 -6
  92. package/src/internals/utils/clientProperties/generateModelsProperty.ts +8 -7
  93. package/src/internals/v6.ts +6 -4
  94. package/src/server/generateClient.ts +4 -1
  95. package/src/types/PubSub.ts +1 -0
  96. package/src/types/index.ts +51 -47
  97. package/src/utils/ConnectionStateMonitor.ts +8 -3
  98. package/src/utils/ReachabilityMonitor/index.native.ts +1 -1
  99. package/src/utils/ReachabilityMonitor/index.ts +1 -0
  100. package/src/utils/ReconnectionMonitor.ts +1 -0
  101. package/src/utils/errors/repackageAuthError.ts +6 -7
  102. package/src/utils/findIndexByFields.ts +1 -1
  103. package/src/utils/resolveConfig.ts +1 -0
  104. package/src/utils/resolveLibraryOptions.ts +1 -0
  105. package/src/utils/resolveOwnerFields.ts +16 -7
  106. package/src/utils/resolvePKFields.ts +1 -0
@@ -1,38 +1,39 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { resolveOwnerFields } from '../utils/resolveOwnerFields';
4
3
  import {
4
+ AssociationBelongsTo,
5
+ AssociationHasOne,
5
6
  GraphQLAuthMode,
6
- ModelIntrospectionSchema,
7
7
  ModelFieldType,
8
+ ModelIntrospectionSchema,
8
9
  NonModelFieldType,
9
10
  SchemaModel,
10
- AssociationHasOne,
11
- AssociationBelongsTo,
11
+ SchemaNonModel,
12
12
  } from '@aws-amplify/core/internals/utils';
13
+ import { AmplifyServer } from '@aws-amplify/core/internals/adapter-core';
14
+ import { CustomHeaders } from '@aws-amplify/data-schema-types';
15
+
13
16
  import {
14
17
  AuthModeParams,
15
18
  ClientWithModels,
16
19
  ListArgs,
17
20
  QueryArgs,
18
21
  V6Client,
19
- V6ClientSSRRequest,
20
22
  __authMode,
21
23
  __authToken,
22
24
  __headers,
23
25
  } from '../types';
24
- import { AmplifyServer } from '@aws-amplify/core/internals/adapter-core';
25
- import { CustomHeaders } from '@aws-amplify/data-schema-types';
26
- import { SchemaNonModel } from '@aws-amplify/core/dist/esm/singleton/API/types';
26
+ import { resolveOwnerFields } from '../utils/resolveOwnerFields';
27
+
27
28
  import type { IndexMeta } from './operations/indexQuery';
28
29
 
29
- type LazyLoadOptions = {
30
+ interface LazyLoadOptions {
30
31
  authMode?: GraphQLAuthMode;
31
32
  authToken?: string | undefined;
32
33
  limit?: number | undefined;
33
34
  nextToken?: string | undefined | null;
34
35
  headers?: CustomHeaders | undefined;
35
- };
36
+ }
36
37
 
37
38
  const connectionType = {
38
39
  HAS_ONE: 'HAS_ONE',
@@ -54,9 +55,11 @@ export const flattenItems = (obj: Record<string, any>): Record<string, any> => {
54
55
  res[prop] = value.items.map((item: Record<string, any>) =>
55
56
  flattenItems(item),
56
57
  );
58
+
57
59
  return;
58
60
  }
59
61
  res[prop] = flattenItems(value);
62
+
60
63
  return;
61
64
  }
62
65
 
@@ -109,15 +112,17 @@ export function initializeModel(
109
112
  connectionFields = modelField.association.associatedWith;
110
113
  }
111
114
 
112
- let targetNames: string[] = [];
115
+ const targetNames: string[] = [];
113
116
  if (modelField.association && 'targetNames' in modelField.association) {
114
- targetNames = modelField.association.targetNames;
117
+ targetNames.push(...modelField.association.targetNames);
115
118
  }
116
119
 
117
120
  switch (relationType) {
118
121
  case connectionType.HAS_ONE:
119
- case connectionType.BELONGS_TO:
122
+ case connectionType.BELONGS_TO: {
120
123
  const sortKeyValues = relatedModelSKFieldNames.reduce(
124
+ // TODO(Eslint): is this implementation correct?
125
+ // eslint-disable-next-line array-callback-return
121
126
  (acc: Record<string, any>, curVal) => {
122
127
  if (record[curVal]) {
123
128
  return (acc[curVal] = record[curVal]);
@@ -132,9 +137,7 @@ export function initializeModel(
132
137
  options?: LazyLoadOptions,
133
138
  ) => {
134
139
  if (record[targetNames[0]]) {
135
- return (
136
- client as V6ClientSSRRequest<Record<string, any>>
137
- ).models[relatedModelName].get(
140
+ return (client as any).models[relatedModelName].get(
138
141
  contextSpec,
139
142
  {
140
143
  [relatedModelPKFieldName]: record[targetNames[0]],
@@ -146,6 +149,7 @@ export function initializeModel(
146
149
  },
147
150
  );
148
151
  }
152
+
149
153
  return undefined;
150
154
  };
151
155
  } else {
@@ -153,9 +157,7 @@ export function initializeModel(
153
157
  options?: LazyLoadOptions,
154
158
  ) => {
155
159
  if (record[targetNames[0]]) {
156
- return (client as V6Client<Record<string, any>>).models[
157
- relatedModelName
158
- ].get(
160
+ return (client as any).models[relatedModelName].get(
159
161
  {
160
162
  [relatedModelPKFieldName]: record[targetNames[0]],
161
163
  ...sortKeyValues,
@@ -166,12 +168,14 @@ export function initializeModel(
166
168
  },
167
169
  );
168
170
  }
171
+
169
172
  return undefined;
170
173
  };
171
174
  }
172
175
 
173
176
  break;
174
- case connectionType.HAS_MANY:
177
+ }
178
+ case connectionType.HAS_MANY: {
175
179
  const parentPk = introModel.primaryKeyInfo.primaryKeyFieldName;
176
180
  const parentSK = introModel.primaryKeyInfo.sortKeyFieldNames;
177
181
 
@@ -204,16 +208,18 @@ export function initializeModel(
204
208
  options?: LazyLoadOptions,
205
209
  ) => {
206
210
  if (record[parentPk]) {
207
- return (
208
- client as V6ClientSSRRequest<Record<string, any>>
209
- ).models[relatedModelName].list(contextSpec, {
210
- filter: { and: hasManyFilter },
211
- limit: options?.limit,
212
- nextToken: options?.nextToken,
213
- authMode: options?.authMode || authMode,
214
- authToken: options?.authToken || authToken,
215
- });
211
+ return (client as any).models[relatedModelName].list(
212
+ contextSpec,
213
+ {
214
+ filter: { and: hasManyFilter },
215
+ limit: options?.limit,
216
+ nextToken: options?.nextToken,
217
+ authMode: options?.authMode || authMode,
218
+ authToken: options?.authToken || authToken,
219
+ },
220
+ );
216
221
  }
222
+
217
223
  return [];
218
224
  };
219
225
  } else {
@@ -221,9 +227,7 @@ export function initializeModel(
221
227
  options?: LazyLoadOptions,
222
228
  ) => {
223
229
  if (record[parentPk]) {
224
- return (client as V6Client<Record<string, any>>).models[
225
- relatedModelName
226
- ].list({
230
+ return (client as any).models[relatedModelName].list({
227
231
  filter: { and: hasManyFilter },
228
232
  limit: options?.limit,
229
233
  nextToken: options?.nextToken,
@@ -231,6 +235,7 @@ export function initializeModel(
231
235
  authToken: options?.authToken || authToken,
232
236
  });
233
237
  }
238
+
234
239
  return [];
235
240
  };
236
241
  }
@@ -254,16 +259,18 @@ export function initializeModel(
254
259
  options?: LazyLoadOptions,
255
260
  ) => {
256
261
  if (record[parentPk]) {
257
- return (
258
- client as V6ClientSSRRequest<Record<string, any>>
259
- ).models[relatedModelName].list(contextSpec, {
260
- filter: { and: hasManyFilter },
261
- limit: options?.limit,
262
- nextToken: options?.nextToken,
263
- authMode: options?.authMode || authMode,
264
- authToken: options?.authToken || authToken,
265
- });
262
+ return (client as any).models[relatedModelName].list(
263
+ contextSpec,
264
+ {
265
+ filter: { and: hasManyFilter },
266
+ limit: options?.limit,
267
+ nextToken: options?.nextToken,
268
+ authMode: options?.authMode || authMode,
269
+ authToken: options?.authToken || authToken,
270
+ },
271
+ );
266
272
  }
273
+
267
274
  return [];
268
275
  };
269
276
  } else {
@@ -271,9 +278,7 @@ export function initializeModel(
271
278
  options?: LazyLoadOptions,
272
279
  ) => {
273
280
  if (record[parentPk]) {
274
- return (client as V6Client<Record<string, any>>).models[
275
- relatedModelName
276
- ].list({
281
+ return (client as any).models[relatedModelName].list({
277
282
  filter: { and: hasManyFilter },
278
283
  limit: options?.limit,
279
284
  nextToken: options?.nextToken,
@@ -281,11 +286,13 @@ export function initializeModel(
281
286
  authToken: options?.authToken || authToken,
282
287
  });
283
288
  }
289
+
284
290
  return [];
285
291
  };
286
292
  }
287
293
 
288
294
  break;
295
+ }
289
296
  default:
290
297
  break;
291
298
  }
@@ -309,9 +316,6 @@ export const graphQLOperationsInfo = {
309
316
  } as const;
310
317
  export type ModelOperation = keyof typeof graphQLOperationsInfo;
311
318
 
312
- type OperationPrefix =
313
- (typeof graphQLOperationsInfo)[ModelOperation]['operationPrefix'];
314
-
315
319
  const SELECTION_SET_WILDCARD = '*';
316
320
 
317
321
  export function defaultSelectionSetForNonModelWithIR(
@@ -346,6 +350,7 @@ export function defaultSelectionSetForNonModelWithIR(
346
350
  pair: (string | Record<string, unknown>)[] | undefined,
347
351
  ): pair is (string | Record<string, unknown>)[] => pair !== undefined,
348
352
  );
353
+
349
354
  return Object.fromEntries(mappedFields);
350
355
  }
351
356
 
@@ -365,6 +370,8 @@ function defaultSelectionSetForModel(modelDefinition: SchemaModel): string[] {
365
370
  return `${name}.${SELECTION_SET_WILDCARD}`;
366
371
  }
367
372
  }
373
+
374
+ return undefined;
368
375
  })
369
376
  .filter(Boolean);
370
377
 
@@ -460,10 +467,13 @@ export function customSelectionSetToIR(
460
467
  }
461
468
 
462
469
  if (nested === SELECTION_SET_WILDCARD) {
463
- const relatedModelDefinition = modelIntrospection.models[relatedModel];
470
+ const nestedRelatedModelDefinition =
471
+ modelIntrospection.models[relatedModel];
464
472
 
465
473
  result = {
466
- [fieldName]: modelsDefaultSelectionSetIR(relatedModelDefinition),
474
+ [fieldName]: modelsDefaultSelectionSetIR(
475
+ nestedRelatedModelDefinition,
476
+ ),
467
477
  };
468
478
  } else {
469
479
  result = {
@@ -527,6 +537,7 @@ const modelsDefaultSelectionSetIR = (relatedModelDefinition: SchemaModel) => {
527
537
  const reduced = defaultSelectionSet.reduce(
528
538
  (acc: Record<string, any>, curVal) => {
529
539
  acc[curVal] = FIELD_IR;
540
+
530
541
  return acc;
531
542
  },
532
543
  {},
@@ -594,9 +605,12 @@ function deepMergeSelectionSetObjects<T extends Record<string, any>>(
594
605
 
595
606
  for (const key in source) {
596
607
  // This verification avoids 'Prototype Pollution' issue
597
- if (!source.hasOwnProperty(key)) continue;
608
+ if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
598
609
 
599
- if (target.hasOwnProperty(key) && isObject(target[key])) {
610
+ if (
611
+ Object.prototype.hasOwnProperty.call(target, key) &&
612
+ isObject(target[key])
613
+ ) {
600
614
  deepMergeSelectionSetObjects(source[key], target[key]);
601
615
  } else {
602
616
  target[key] = source[key];
@@ -659,6 +673,7 @@ export function generateGraphQLDocument(
659
673
  const skQueryArgs = sk.reduce((acc: Record<string, any>, fieldName) => {
660
674
  const fieldType = fields[fieldName].type;
661
675
  acc[fieldName] = `Model${fieldType}KeyConditionInput`;
676
+
662
677
  return acc;
663
678
  }, {});
664
679
 
@@ -694,6 +709,8 @@ export function generateGraphQLDocument(
694
709
  }${name}Input!`,
695
710
  });
696
711
  graphQLOperationType ?? (graphQLOperationType = 'mutation');
712
+ // TODO(Eslint): this this case clause correct without the break statement?
713
+ // eslint-disable-next-line no-fallthrough
697
714
  case 'READ':
698
715
  graphQLArguments ??
699
716
  (graphQLArguments = isCustomPrimaryKey
@@ -709,6 +726,8 @@ export function generateGraphQLDocument(
709
726
  [primaryKeyFieldName]: `${fields[primaryKeyFieldName].type}!`,
710
727
  });
711
728
  graphQLSelectionSet ?? (graphQLSelectionSet = selectionSetFields);
729
+ // TODO(Eslint): this this case clause correct without the break statement?
730
+ // eslint-disable-next-line no-fallthrough
712
731
  case 'LIST':
713
732
  graphQLArguments ??
714
733
  (graphQLArguments = {
@@ -719,6 +738,8 @@ export function generateGraphQLDocument(
719
738
  graphQLOperationType ?? (graphQLOperationType = 'query');
720
739
  graphQLSelectionSet ??
721
740
  (graphQLSelectionSet = `items { ${selectionSetFields} } nextToken __typename`);
741
+ // TODO(Eslint): this this case clause correct without the break statement?
742
+ // eslint-disable-next-line no-fallthrough
722
743
  case 'INDEX_QUERY':
723
744
  graphQLArguments ??
724
745
  (graphQLArguments = {
@@ -730,6 +751,8 @@ export function generateGraphQLDocument(
730
751
  graphQLOperationType ?? (graphQLOperationType = 'query');
731
752
  graphQLSelectionSet ??
732
753
  (graphQLSelectionSet = `items { ${selectionSetFields} } nextToken __typename`);
754
+ // TODO(Eslint): this this case clause correct without the break statement?
755
+ // eslint-disable-next-line no-fallthrough
733
756
  case 'ONCREATE':
734
757
  case 'ONUPDATE':
735
758
  case 'ONDELETE':
@@ -750,13 +773,13 @@ export function generateGraphQLDocument(
750
773
  const graphQLDocument = `${graphQLOperationType}${
751
774
  graphQLArguments
752
775
  ? `(${Object.entries(graphQLArguments).map(
753
- ([fieldName, type]) => `\$${fieldName}: ${type}`,
776
+ ([fieldName, type]) => `$${fieldName}: ${type}`,
754
777
  )})`
755
778
  : ''
756
779
  } { ${graphQLFieldName}${
757
780
  graphQLArguments
758
781
  ? `(${Object.keys(graphQLArguments).map(
759
- fieldName => `${fieldName}: \$${fieldName}`,
782
+ fieldName => `${fieldName}: $${fieldName}`,
760
783
  )})`
761
784
  : ''
762
785
  } { ${graphQLSelectionSet} } }`;
@@ -842,7 +865,7 @@ export function buildGraphQLVariables(
842
865
  variables.limit = arg.limit;
843
866
  }
844
867
  break;
845
- case 'INDEX_QUERY':
868
+ case 'INDEX_QUERY': {
846
869
  const { pk, sk = [] } = indexMeta!;
847
870
 
848
871
  variables[pk] = arg![pk];
@@ -861,6 +884,7 @@ export function buildGraphQLVariables(
861
884
  variables.limit = arg.limit;
862
885
  }
863
886
  break;
887
+ }
864
888
  case 'ONCREATE':
865
889
  case 'ONUPDATE':
866
890
  case 'ONDELETE':
@@ -873,9 +897,10 @@ export function buildGraphQLVariables(
873
897
  'Internal error: Attempted to build variables for observeQuery. Please report this error.',
874
898
  );
875
899
  break;
876
- default:
900
+ default: {
877
901
  const exhaustiveCheck: never = operation;
878
902
  throw new Error(`Unhandled operation case: ${exhaustiveCheck}`);
903
+ }
879
904
  }
880
905
 
881
906
  return variables;
@@ -969,9 +994,9 @@ export function authModeParams(
969
994
 
970
995
  /**
971
996
  * Retrieves custom headers from either the client or request options.
972
- * @param {client} V6Client | V6ClientSSRRequest | V6ClientSSRCookies - for extracting client headers
973
- * @param {requestHeaders} [CustomHeaders] - request headers
974
- * @returns {CustomHeaders} - custom headers
997
+ * @param client V6Client | V6ClientSSRRequest | V6ClientSSRCookies - for extracting client headers
998
+ * @param requestHeaders {@link CustomHeaders} - request headers
999
+ * @returns custom headers as {@link CustomHeaders}
975
1000
  */
976
1001
  export function getCustomHeaders(
977
1002
  client: V6Client | ClientWithModels,
@@ -2,41 +2,40 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  import {
4
4
  DocumentNode,
5
- OperationDefinitionNode,
6
- print,
7
- parse,
8
5
  GraphQLError,
6
+ OperationDefinitionNode,
9
7
  OperationTypeNode,
8
+ parse,
9
+ print,
10
10
  } from 'graphql';
11
11
  import { Observable, catchError } from 'rxjs';
12
- import { AmplifyClassV6, ConsoleLogger } from '@aws-amplify/core';
12
+ import { AmplifyClassV6 } from '@aws-amplify/core';
13
13
  import {
14
- GraphQLAuthMode,
14
+ AmplifyUrl,
15
15
  CustomUserAgentDetails,
16
+ GraphQLAuthMode,
16
17
  getAmplifyUserAgent,
17
- AmplifyUrl,
18
18
  } from '@aws-amplify/core/internals/utils';
19
- import {
20
- GraphQLAuthError,
21
- GraphQLResult,
22
- GraphQLOperation,
23
- GraphQLOptions,
24
- } from '../types';
25
19
  import { isCancelError as isCancelErrorREST } from '@aws-amplify/api-rest';
26
20
  import {
27
- post,
28
21
  cancel as cancelREST,
22
+ post,
29
23
  updateRequestToBeCancellable,
30
24
  } from '@aws-amplify/api-rest/internals';
31
- import { AWSAppSyncRealTimeProvider } from '../Providers/AWSAppSyncRealTimeProvider';
32
25
  import { CustomHeaders, RequestOptions } from '@aws-amplify/data-schema-types';
26
+
27
+ import { AWSAppSyncRealTimeProvider } from '../Providers/AWSAppSyncRealTimeProvider';
28
+ import {
29
+ GraphQLAuthError,
30
+ GraphQLOperation,
31
+ GraphQLOptions,
32
+ GraphQLResult,
33
+ } from '../types';
33
34
  import { resolveConfig, resolveLibraryOptions } from '../utils';
34
35
  import { repackageUnauthError } from '../utils/errors/repackageAuthError';
35
36
 
36
37
  const USER_AGENT_HEADER = 'x-amz-user-agent';
37
38
 
38
- const logger = new ConsoleLogger('GraphQLAPI');
39
-
40
39
  const isAmplifyInstance = (
41
40
  amplify:
42
41
  | AmplifyClassV6
@@ -70,11 +69,7 @@ export class InternalGraphQLAPIClass {
70
69
  authMode: GraphQLAuthMode,
71
70
  additionalHeaders: Record<string, string> = {},
72
71
  ) {
73
- const {
74
- region: region,
75
- endpoint: appSyncGraphqlEndpoint,
76
- apiKey,
77
- } = resolveConfig(amplify);
72
+ const { apiKey } = resolveConfig(amplify);
78
73
 
79
74
  let headers = {};
80
75
 
@@ -87,18 +82,17 @@ export class InternalGraphQLAPIClass {
87
82
  'X-Api-Key': apiKey,
88
83
  };
89
84
  break;
90
- case 'iam':
85
+ case 'iam': {
91
86
  const session = await amplify.Auth.fetchAuthSession();
92
87
  if (session.credentials === undefined) {
93
88
  throw new Error(GraphQLAuthError.NO_CREDENTIALS);
94
89
  }
95
90
  break;
91
+ }
96
92
  case 'oidc':
97
93
  case 'userPool':
98
94
  try {
99
- let token;
100
-
101
- token = (
95
+ const token = (
102
96
  await amplify.Auth.fetchAuthSession()
103
97
  ).tokens?.accessToken.toString();
104
98
 
@@ -139,8 +133,7 @@ export class InternalGraphQLAPIClass {
139
133
  */
140
134
  getGraphqlOperationType(operation: GraphQLOperation): OperationTypeNode {
141
135
  const doc = parse(operation);
142
- const definitions =
143
- doc.definitions as ReadonlyArray<OperationDefinitionNode>;
136
+ const definitions = doc.definitions as readonly OperationDefinitionNode[];
144
137
  const [{ operation: operationType }] = definitions;
145
138
 
146
139
  return operationType;
@@ -176,7 +169,7 @@ export class InternalGraphQLAPIClass {
176
169
 
177
170
  switch (operationType) {
178
171
  case 'query':
179
- case 'mutation':
172
+ case 'mutation': {
180
173
  const abortController = new AbortController();
181
174
 
182
175
  let responsePromise: Promise<GraphQLResult<T>>;
@@ -215,7 +208,9 @@ export class InternalGraphQLAPIClass {
215
208
  responsePromise,
216
209
  abortController,
217
210
  );
211
+
218
212
  return responsePromise;
213
+ }
219
214
  case 'subscription':
220
215
  return this._graphqlSubscribe(
221
216
  amplify as AmplifyClassV6,
@@ -238,7 +233,7 @@ export class InternalGraphQLAPIClass {
238
233
  authToken?: string,
239
234
  ): Promise<GraphQLResult<T>> {
240
235
  const {
241
- region: region,
236
+ region,
242
237
  endpoint: appSyncGraphqlEndpoint,
243
238
  customEndpoint,
244
239
  customEndpointRegion,
@@ -356,7 +351,8 @@ export class InternalGraphQLAPIClass {
356
351
 
357
352
  if (!endpoint) {
358
353
  const error = new GraphQLError('No graphql endpoint provided.');
359
-
354
+ // TODO(Eslint): refactor this to throw an Error instead of a plain object
355
+ // eslint-disable-next-line no-throw-literal
360
356
  throw {
361
357
  data: {},
362
358
  errors: [error],
@@ -2,8 +2,8 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  import type {
5
- SchemaModel,
6
5
  ModelAttribute,
6
+ SchemaModel,
7
7
  SecondaryIndexAttribute,
8
8
  } from '@aws-amplify/core/internals/utils';
9
9
 
@@ -1,20 +1,14 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  import { Hub } from '@aws-amplify/core';
4
- import { graphql, cancel, isCancelError } from './v6';
5
4
  import {
5
+ CustomMutations,
6
+ CustomQueries,
7
+ CustomSubscriptions,
6
8
  EnumTypes,
7
9
  ModelTypes,
8
- CustomQueries,
9
- CustomMutations,
10
10
  } from '@aws-amplify/data-schema-types';
11
- import { generateEnumsProperty } from './utils/clientProperties/generateEnumsProperty';
12
- import { generateModelsProperty } from './utils/clientProperties/generateModelsProperty';
13
- import { isApiGraphQLConfig } from './utils/runtimeTypeGuards/isApiGraphQLProviderConfig';
14
- import {
15
- generateCustomQueriesProperty,
16
- generateCustomMutationsProperty,
17
- } from './generateCustomOperationsProperty';
11
+
18
12
  import {
19
13
  V6Client,
20
14
  __amplify,
@@ -22,6 +16,16 @@ import {
22
16
  __authToken,
23
17
  __headers,
24
18
  } from '../types';
19
+
20
+ import { cancel, graphql, isCancelError } from './v6';
21
+ import { generateEnumsProperty } from './utils/clientProperties/generateEnumsProperty';
22
+ import { generateModelsProperty } from './utils/clientProperties/generateModelsProperty';
23
+ import { isApiGraphQLConfig } from './utils/runtimeTypeGuards/isApiGraphQLProviderConfig';
24
+ import {
25
+ generateCustomMutationsProperty,
26
+ generateCustomQueriesProperty,
27
+ generateCustomSubscriptionsProperty,
28
+ } from './generateCustomOperationsProperty';
25
29
  import { ClientGenerationParams } from './types';
26
30
  import { isConfigureEventWithResourceConfig } from './utils/runtimeTypeGuards/isConfigureEventWithResourceConfig';
27
31
 
@@ -49,6 +53,7 @@ export function generateClient<T extends Record<any, any> = never>(
49
53
  enums: emptyProperty as EnumTypes<never>,
50
54
  queries: emptyProperty as CustomQueries<never>,
51
55
  mutations: emptyProperty as CustomMutations<never>,
56
+ subscriptions: emptyProperty as CustomSubscriptions<never>,
52
57
  } as any;
53
58
 
54
59
  const apiGraphqlConfig = params.amplify.getConfig().API?.GraphQL;
@@ -61,6 +66,10 @@ export function generateClient<T extends Record<any, any> = never>(
61
66
  client,
62
67
  apiGraphqlConfig,
63
68
  );
69
+ client.subscriptions = generateCustomSubscriptionsProperty(
70
+ client,
71
+ apiGraphqlConfig,
72
+ );
64
73
  } else {
65
74
  // This happens when the `Amplify.configure()` call gets evaluated after the `generateClient()` call.
66
75
  //
@@ -99,6 +108,10 @@ const generateModelsPropertyOnAmplifyConfigure = (clientRef: any) => {
99
108
  clientRef,
100
109
  apiGraphQLConfig,
101
110
  );
111
+ clientRef.subscriptions = generateCustomSubscriptionsProperty(
112
+ clientRef,
113
+ apiGraphQLConfig,
114
+ );
102
115
  }
103
116
  });
104
117
  };
@@ -1,24 +1,36 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { CustomQueries, CustomMutations } from '@aws-amplify/data-schema-types';
4
- import { V6Client, __authMode, __authToken, __amplify } from '../types';
5
-
6
- import { customOpFactory } from './operations/custom';
7
3
  import {
8
- ModelIntrospectionSchema,
4
+ CustomMutations,
5
+ CustomQueries,
6
+ CustomSubscriptions,
7
+ } from '@aws-amplify/data-schema-types';
8
+ import {
9
9
  GraphQLProviderConfig,
10
+ ModelIntrospectionSchema,
10
11
  } from '@aws-amplify/core/internals/utils';
11
12
 
12
- type OpTypes = 'queries' | 'mutations';
13
+ import { V6Client, __amplify } from '../types';
14
+
15
+ import { customOpFactory } from './operations/custom';
16
+
17
+ type OpTypes = 'queries' | 'mutations' | 'subscriptions';
13
18
 
14
19
  type CustomOpsProperty<
15
20
  T extends Record<any, any>,
16
21
  OpType extends OpTypes,
17
- > = OpType extends 'queries' ? CustomQueries<T> : CustomMutations<T>;
22
+ > = OpType extends 'queries'
23
+ ? CustomQueries<T>
24
+ : OpType extends 'mutations'
25
+ ? CustomMutations<T>
26
+ : OpType extends 'subscriptions'
27
+ ? CustomSubscriptions<T>
28
+ : never;
18
29
 
19
30
  const operationTypeMap = {
20
31
  queries: 'query',
21
32
  mutations: 'mutation',
33
+ subscriptions: 'subscription',
22
34
  } as const;
23
35
 
24
36
  export function generateCustomOperationsProperty<
@@ -59,7 +71,7 @@ export function generateCustomOperationsProperty<
59
71
  modelIntrospection,
60
72
  operationTypeMap[operationsType],
61
73
  operation,
62
- useContext
74
+ useContext,
63
75
  );
64
76
  }
65
77
 
@@ -87,3 +99,14 @@ export function generateCustomQueriesProperty<T extends Record<any, any>>(
87
99
  'queries',
88
100
  );
89
101
  }
102
+
103
+ export function generateCustomSubscriptionsProperty<T extends Record<any, any>>(
104
+ client: V6Client<Record<string, any>>,
105
+ config: GraphQLProviderConfig['GraphQL'],
106
+ ) {
107
+ return generateCustomOperationsProperty<T, 'subscriptions'>(
108
+ client,
109
+ config,
110
+ 'subscriptions',
111
+ );
112
+ }