@aws-amplify/api-graphql 4.0.1-console-preview.be08038.0 → 4.0.1-server-generate-client.1e317a1.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 (80) hide show
  1. package/lib/GraphQLAPI.d.ts +2 -2
  2. package/lib/GraphQLAPI.js +4 -6
  3. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +1 -1
  4. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +36 -36
  5. package/lib/Providers/constants.js +5 -4
  6. package/lib/index.js +5 -4
  7. package/lib/internals/APIClient.d.ts +101 -0
  8. package/lib/internals/APIClient.js +443 -0
  9. package/lib/internals/InternalGraphQLAPI.d.ts +2 -2
  10. package/lib/internals/InternalGraphQLAPI.js +35 -17
  11. package/lib/internals/generateClient.d.ts +12 -0
  12. package/lib/internals/generateClient.js +30 -0
  13. package/lib/internals/generateModelsProperty.d.ts +4 -0
  14. package/lib/internals/generateModelsProperty.js +169 -0
  15. package/lib/internals/index.d.ts +1 -0
  16. package/lib/internals/index.js +8 -5
  17. package/lib/internals/types.d.ts +10 -0
  18. package/lib/internals/types.js +2 -0
  19. package/lib/internals/v6.js +1 -0
  20. package/lib/tsconfig.tsbuildinfo +1 -6619
  21. package/lib/types/PubSub.d.ts +2 -2
  22. package/lib/types/PubSub.js +3 -2
  23. package/lib/types/index.d.ts +25 -22
  24. package/lib/types/index.js +4 -3
  25. package/lib/utils/ConnectionStateMonitor.d.ts +3 -3
  26. package/lib/utils/ConnectionStateMonitor.js +7 -6
  27. package/lib/utils/ReachabilityMonitor/index.d.ts +1 -1
  28. package/lib/utils/ReachabilityMonitor/index.js +3 -1
  29. package/lib/utils/ReachabilityMonitor/index.native.d.ts +1 -1
  30. package/lib/utils/ReachabilityMonitor/index.native.js +3 -1
  31. package/lib/utils/ReconnectionMonitor.js +2 -1
  32. package/lib/utils/errors/APIError.js +1 -0
  33. package/lib/utils/errors/assertValidationError.js +1 -0
  34. package/lib/utils/errors/index.js +5 -4
  35. package/lib/utils/errors/validation.js +2 -1
  36. package/lib/utils/index.js +3 -2
  37. package/lib/utils/resolveConfig.d.ts +1 -1
  38. package/lib/utils/resolveConfig.js +4 -2
  39. package/lib/utils/resolveLibraryOptions.d.ts +1 -1
  40. package/lib/utils/resolveLibraryOptions.js +3 -1
  41. package/lib/utils/resolveOwnerFields.d.ts +12 -0
  42. package/lib/utils/resolveOwnerFields.js +63 -0
  43. package/lib-esm/GraphQLAPI.d.ts +2 -2
  44. package/lib-esm/GraphQLAPI.js +1 -5
  45. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +1 -1
  46. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +28 -29
  47. package/lib-esm/internals/APIClient.d.ts +101 -0
  48. package/lib-esm/internals/APIClient.js +432 -0
  49. package/lib-esm/internals/InternalGraphQLAPI.d.ts +2 -2
  50. package/lib-esm/internals/InternalGraphQLAPI.js +21 -5
  51. package/lib-esm/internals/generateClient.d.ts +12 -0
  52. package/lib-esm/internals/generateClient.js +26 -0
  53. package/lib-esm/internals/generateModelsProperty.d.ts +4 -0
  54. package/lib-esm/internals/generateModelsProperty.js +165 -0
  55. package/lib-esm/internals/index.d.ts +1 -0
  56. package/lib-esm/internals/index.js +1 -0
  57. package/lib-esm/internals/types.d.ts +10 -0
  58. package/lib-esm/internals/types.js +1 -0
  59. package/lib-esm/tsconfig.tsbuildinfo +1 -6619
  60. package/lib-esm/types/PubSub.d.ts +2 -2
  61. package/lib-esm/types/index.d.ts +25 -22
  62. package/lib-esm/utils/ConnectionStateMonitor.d.ts +3 -3
  63. package/lib-esm/utils/ConnectionStateMonitor.js +2 -2
  64. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +1 -1
  65. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +1 -1
  66. package/lib-esm/utils/resolveConfig.d.ts +1 -1
  67. package/lib-esm/utils/resolveLibraryOptions.d.ts +1 -1
  68. package/lib-esm/utils/resolveOwnerFields.d.ts +12 -0
  69. package/lib-esm/utils/resolveOwnerFields.js +59 -0
  70. package/package.json +12 -6
  71. package/src/GraphQLAPI.ts +2 -6
  72. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +2 -3
  73. package/src/internals/APIClient.ts +583 -0
  74. package/src/internals/InternalGraphQLAPI.ts +35 -9
  75. package/src/internals/generateClient.ts +30 -0
  76. package/src/internals/generateModelsProperty.ts +192 -0
  77. package/src/internals/index.ts +1 -0
  78. package/src/internals/types.ts +15 -0
  79. package/src/types/index.ts +7 -1
  80. package/src/utils/resolveOwnerFields.ts +65 -0
@@ -0,0 +1,432 @@
1
+ import { __assign, __read, __spreadArray, __values } from "tslib";
2
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { resolveOwnerFields } from '../utils/resolveOwnerFields';
5
+ var connectionType = {
6
+ HAS_ONE: 'HAS_ONE',
7
+ HAS_MANY: 'HAS_MANY',
8
+ BELONGS_TO: 'BELONGS_TO',
9
+ };
10
+ /**
11
+ *
12
+ * @param GraphQL response object
13
+ * @returns response object with `items` properties flattened
14
+ */
15
+ export var flattenItems = function (obj) {
16
+ var res = {};
17
+ Object.entries(obj).forEach(function (_a) {
18
+ var _b = __read(_a, 2), prop = _b[0], value = _b[1];
19
+ if (typeof value === 'object' && value !== null) {
20
+ if (value.items !== undefined) {
21
+ res[prop] = value.items.map(function (item) {
22
+ return flattenItems(item);
23
+ });
24
+ return;
25
+ }
26
+ res[prop] = flattenItems(value);
27
+ return;
28
+ }
29
+ res[prop] = value;
30
+ });
31
+ return res;
32
+ };
33
+ // TODO: this should accept single result to support CRUD methods; create helper for array/list
34
+ export function initializeModel(client, modelName, result, modelIntrospection) {
35
+ var introModel = modelIntrospection.models[modelName];
36
+ var introModelFields = introModel.fields;
37
+ var modelFields = Object.entries(introModelFields)
38
+ .filter(function (_a) {
39
+ var _b;
40
+ var _c = __read(_a, 2), _ = _c[0], field = _c[1];
41
+ return ((_b = field === null || field === void 0 ? void 0 : field.type) === null || _b === void 0 ? void 0 : _b.model) !== undefined;
42
+ })
43
+ .map(function (_a) {
44
+ var _b = __read(_a, 1), fieldName = _b[0];
45
+ return fieldName;
46
+ });
47
+ return result.map(function (record) {
48
+ var e_1, _a;
49
+ var _b, _c;
50
+ var initializedRelationalFields = {};
51
+ var _loop_1 = function (field) {
52
+ var relatedModelName = introModelFields[field].type.model;
53
+ var relatedModel = modelIntrospection.models[relatedModelName];
54
+ var relatedModelPKFieldName = relatedModel.primaryKeyInfo.primaryKeyFieldName;
55
+ var relatedModelSKFieldNames = relatedModel.primaryKeyInfo.sortKeyFieldNames;
56
+ var relationType = introModelFields[field].association.connectionType;
57
+ var connectionFields = introModelFields[field].association.associatedWith;
58
+ var targetNames = ((_b = introModelFields[field].association) === null || _b === void 0 ? void 0 : _b.targetNames) || [];
59
+ switch (relationType) {
60
+ case connectionType.HAS_ONE:
61
+ case connectionType.BELONGS_TO:
62
+ var sortKeyValues_1 = relatedModelSKFieldNames.reduce(function (acc, curVal) {
63
+ if (record[curVal]) {
64
+ return (acc[curVal] = record[curVal]);
65
+ }
66
+ }, {});
67
+ initializedRelationalFields[field] = function () {
68
+ var _a;
69
+ if (record[targetNames[0]]) {
70
+ return client.models[relatedModelName].get(__assign((_a = {}, _a[relatedModelPKFieldName] = record[targetNames[0]], _a), sortKeyValues_1));
71
+ }
72
+ return undefined;
73
+ };
74
+ break;
75
+ case connectionType.HAS_MANY:
76
+ var parentPk_1 = introModel.primaryKeyInfo.primaryKeyFieldName;
77
+ var parentSK_1 = introModel.primaryKeyInfo.sortKeyFieldNames;
78
+ // M:N check - TODO: refactor
79
+ if ((_c = relatedModel.fields[connectionFields[0]]) === null || _c === void 0 ? void 0 : _c.type.model) {
80
+ var relatedTargetNames = relatedModel.fields[connectionFields[0]].association.targetNames;
81
+ var hasManyFilter_1 = relatedTargetNames.map(function (field, idx) {
82
+ var _a, _b;
83
+ if (idx === 0) {
84
+ return _a = {}, _a[field] = { eq: record[parentPk_1] }, _a;
85
+ }
86
+ return _b = {}, _b[field] = { eq: record[parentSK_1[idx - 1]] }, _b;
87
+ });
88
+ initializedRelationalFields[field] = function () {
89
+ if (record[parentPk_1]) {
90
+ return client.models[relatedModelName].list({
91
+ filter: { and: hasManyFilter_1 },
92
+ });
93
+ }
94
+ return [];
95
+ };
96
+ break;
97
+ }
98
+ var hasManyFilter_2 = connectionFields.map(function (field, idx) {
99
+ var _a, _b;
100
+ if (idx === 0) {
101
+ return _a = {}, _a[field] = { eq: record[parentPk_1] }, _a;
102
+ }
103
+ return _b = {}, _b[field] = { eq: record[parentSK_1[idx - 1]] }, _b;
104
+ });
105
+ initializedRelationalFields[field] = function () {
106
+ if (record[parentPk_1]) {
107
+ return client.models[relatedModelName].list({
108
+ filter: { and: hasManyFilter_2 },
109
+ });
110
+ }
111
+ return [];
112
+ };
113
+ break;
114
+ default:
115
+ break;
116
+ }
117
+ };
118
+ try {
119
+ for (var modelFields_1 = __values(modelFields), modelFields_1_1 = modelFields_1.next(); !modelFields_1_1.done; modelFields_1_1 = modelFields_1.next()) {
120
+ var field = modelFields_1_1.value;
121
+ _loop_1(field);
122
+ }
123
+ }
124
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
125
+ finally {
126
+ try {
127
+ if (modelFields_1_1 && !modelFields_1_1.done && (_a = modelFields_1.return)) _a.call(modelFields_1);
128
+ }
129
+ finally { if (e_1) throw e_1.error; }
130
+ }
131
+ return __assign(__assign({}, record), initializedRelationalFields);
132
+ });
133
+ }
134
+ export var graphQLOperationsInfo = {
135
+ CREATE: { operationPrefix: 'create', usePlural: false },
136
+ READ: { operationPrefix: 'get', usePlural: false },
137
+ UPDATE: { operationPrefix: 'update', usePlural: false },
138
+ DELETE: { operationPrefix: 'delete', usePlural: false },
139
+ LIST: { operationPrefix: 'list', usePlural: true },
140
+ ONCREATE: { operationPrefix: 'onCreate', usePlural: false },
141
+ ONUPDATE: { operationPrefix: 'onUpdate', usePlural: false },
142
+ ONDELETE: { operationPrefix: 'onDelete', usePlural: false },
143
+ };
144
+ var graphQLDocumentsCache = new Map();
145
+ var SELECTION_SET_WILDCARD = '*';
146
+ function defaultSelectionSetForModel(modelDefinition) {
147
+ // fields that are explicitly part of the graphql schema; not
148
+ // inferred from owner auth rules.
149
+ var fields = modelDefinition.fields;
150
+ var explicitFields = Object.values(fields)
151
+ .map(function (_a) {
152
+ var type = _a.type, name = _a.name;
153
+ return typeof type === 'string' && name;
154
+ }) // Default selection set omits model fields
155
+ .filter(Boolean);
156
+ // fields used for owner auth rules that may or may not also
157
+ // be explicit on the model.
158
+ var ownerFields = resolveOwnerFields(modelDefinition);
159
+ return Array.from(new Set(explicitFields.concat(ownerFields)));
160
+ }
161
+ var FIELD_IR = '';
162
+ /**
163
+ * Generates nested Custom Selection Set IR from path
164
+ *
165
+ * @param modelIntrospection
166
+ * @param modelName
167
+ * @param selectionSet - array of object paths
168
+ * @example
169
+ * ### Given
170
+ * `selectionSet = ['id', 'comments.post.id']`
171
+ * ### Returns
172
+ * ```ts
173
+ * {
174
+ * id: '',
175
+ * comments: {
176
+ * items: { post: { id: '' } }
177
+ * }
178
+ * }
179
+ * ```
180
+ */
181
+ export function customSelectionSetToIR(modelIntrospection, modelName, selectionSet) {
182
+ var modelDefinition = modelIntrospection[modelName];
183
+ var modelFields = modelDefinition.fields;
184
+ return selectionSet.reduce(function (resultObj, path) {
185
+ var _a, _b, _c;
186
+ var _d = __read(path.split('.')), fieldName = _d[0], nested = _d[1], rest = _d.slice(2);
187
+ if (nested) {
188
+ var relatedModel = (_b = (_a = modelFields[fieldName]) === null || _a === void 0 ? void 0 : _a.type) === null || _b === void 0 ? void 0 : _b.model;
189
+ if (!relatedModel) {
190
+ // TODO: may need to change this to support custom types
191
+ throw Error("".concat(fieldName, " is not a model field"));
192
+ }
193
+ var relatedModelDefinition = modelIntrospection[relatedModel];
194
+ var selectionSet_1 = nested === SELECTION_SET_WILDCARD
195
+ ? defaultSelectionSetIR(relatedModelDefinition)
196
+ : // if we have a path like 'field.anotherField' recursively build up selection set IR
197
+ customSelectionSetToIR(modelIntrospection, relatedModel, [
198
+ __spreadArray([nested], __read(rest), false).join('.'),
199
+ ]);
200
+ if ((_c = modelFields[fieldName]) === null || _c === void 0 ? void 0 : _c.isArray) {
201
+ var existing = resultObj[fieldName] || {
202
+ items: {},
203
+ };
204
+ var merged_1 = __assign(__assign({}, existing.items), selectionSet_1);
205
+ resultObj[fieldName] = { items: merged_1 };
206
+ return resultObj;
207
+ }
208
+ var existingItems = resultObj[fieldName] || {};
209
+ var merged = __assign(__assign({}, existingItems), selectionSet_1);
210
+ resultObj[fieldName] = merged;
211
+ return resultObj;
212
+ }
213
+ var exists = Boolean(modelFields[fieldName]);
214
+ if (!exists) {
215
+ throw Error("".concat(fieldName, " is not a field of model ").concat(modelName));
216
+ }
217
+ resultObj[fieldName] = FIELD_IR;
218
+ return resultObj;
219
+ }, {});
220
+ }
221
+ var defaultSelectionSetIR = function (relatedModelDefinition) {
222
+ var defaultSelectionSet = defaultSelectionSetForModel(relatedModelDefinition);
223
+ var reduced = defaultSelectionSet.reduce(function (acc, curVal) {
224
+ acc[curVal] = FIELD_IR;
225
+ return acc;
226
+ }, {});
227
+ return reduced;
228
+ };
229
+ /**
230
+ * Stringifies selection set IR
231
+ * * @example
232
+ * ### Given
233
+ * ```ts
234
+ * {
235
+ * id: '',
236
+ * comments: {
237
+ * items: { post: { id: '' } }
238
+ * }
239
+ * }
240
+ * ```
241
+ * ### Returns
242
+ * `'id comments { items { post { id } } }'`
243
+ */
244
+ export function selectionSetIRToString(obj) {
245
+ var res = [];
246
+ Object.entries(obj).forEach(function (_a) {
247
+ var _b = __read(_a, 2), fieldName = _b[0], value = _b[1];
248
+ if (value === FIELD_IR) {
249
+ res.push(fieldName);
250
+ }
251
+ else if (typeof value === 'object' && value !== null) {
252
+ if (value === null || value === void 0 ? void 0 : value.items) {
253
+ res.push(fieldName, '{', 'items', '{', selectionSetIRToString(value.items), '}', '}');
254
+ }
255
+ else {
256
+ res.push(fieldName, '{', selectionSetIRToString(value), '}');
257
+ }
258
+ }
259
+ });
260
+ return res.join(' ');
261
+ }
262
+ export function generateSelectionSet(modelIntrospection, modelName, selectionSet) {
263
+ var modelDefinition = modelIntrospection[modelName];
264
+ if (!selectionSet) {
265
+ return defaultSelectionSetForModel(modelDefinition).join(' ');
266
+ }
267
+ var selSetIr = customSelectionSetToIR(modelIntrospection, modelName, selectionSet);
268
+ var selSetString = selectionSetIRToString(selSetIr);
269
+ return selSetString;
270
+ }
271
+ export function generateGraphQLDocument(modelIntrospection, modelName, modelOperation, listArgs) {
272
+ var _a;
273
+ var _b, _c;
274
+ var modelDefinition = modelIntrospection[modelName];
275
+ var name = modelDefinition.name, pluralName = modelDefinition.pluralName, fields = modelDefinition.fields, _d = modelDefinition.primaryKeyInfo, isCustomPrimaryKey = _d.isCustomPrimaryKey, primaryKeyFieldName = _d.primaryKeyFieldName, sortKeyFieldNames = _d.sortKeyFieldNames;
276
+ var _e = graphQLOperationsInfo[modelOperation], operationPrefix = _e.operationPrefix, usePlural = _e.usePlural;
277
+ var selectionSet = (listArgs || {}).selectionSet;
278
+ var fromCache = (_b = graphQLDocumentsCache.get(name)) === null || _b === void 0 ? void 0 : _b.get(modelOperation);
279
+ if (fromCache !== undefined) {
280
+ return fromCache;
281
+ }
282
+ if (!graphQLDocumentsCache.has(name)) {
283
+ graphQLDocumentsCache.set(name, new Map());
284
+ }
285
+ var graphQLFieldName = "".concat(operationPrefix).concat(usePlural ? pluralName : name);
286
+ var graphQLOperationType;
287
+ var graphQLSelectionSet;
288
+ var graphQLArguments;
289
+ var selectionSetFields = generateSelectionSet(modelIntrospection, modelName, selectionSet);
290
+ switch (modelOperation) {
291
+ case 'CREATE':
292
+ case 'UPDATE':
293
+ case 'DELETE':
294
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = {
295
+ input: "".concat(operationPrefix.charAt(0).toLocaleUpperCase() +
296
+ operationPrefix.slice(1)).concat(name, "Input!"),
297
+ });
298
+ graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'mutation');
299
+ case 'READ':
300
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = isCustomPrimaryKey
301
+ ? __spreadArray([primaryKeyFieldName], __read(sortKeyFieldNames), false).reduce(function (acc, fieldName) {
302
+ acc[fieldName] = fields[fieldName].type;
303
+ return acc;
304
+ }, {})
305
+ : (_a = {},
306
+ _a[primaryKeyFieldName] = "".concat(fields[primaryKeyFieldName].type, "!"),
307
+ _a));
308
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = selectionSetFields);
309
+ case 'LIST':
310
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = {
311
+ filter: "Model".concat(name, "FilterInput"),
312
+ });
313
+ graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'query');
314
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = "items { ".concat(selectionSetFields, " }"));
315
+ case 'ONCREATE':
316
+ case 'ONUPDATE':
317
+ case 'ONDELETE':
318
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = {
319
+ filter: "ModelSubscription".concat(name, "FilterInput"),
320
+ });
321
+ graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'subscription');
322
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = selectionSetFields);
323
+ }
324
+ var graphQLDocument = "".concat(graphQLOperationType).concat(graphQLArguments
325
+ ? "(".concat(Object.entries(graphQLArguments).map(function (_a) {
326
+ var _b = __read(_a, 2), fieldName = _b[0], type = _b[1];
327
+ return "$".concat(fieldName, ": ").concat(type);
328
+ }), ")")
329
+ : '', " { ").concat(graphQLFieldName).concat(graphQLArguments
330
+ ? "(".concat(Object.keys(graphQLArguments).map(function (fieldName) { return "".concat(fieldName, ": $").concat(fieldName); }), ")")
331
+ : '', " { ").concat(graphQLSelectionSet, " } }");
332
+ (_c = graphQLDocumentsCache.get(name)) === null || _c === void 0 ? void 0 : _c.set(modelOperation, graphQLDocument);
333
+ return graphQLDocument;
334
+ }
335
+ export function buildGraphQLVariables(modelDefinition, operation, arg, modelIntrospection) {
336
+ var _a;
337
+ var fields = modelDefinition.fields, _b = modelDefinition.primaryKeyInfo, isCustomPrimaryKey = _b.isCustomPrimaryKey, primaryKeyFieldName = _b.primaryKeyFieldName, sortKeyFieldNames = _b.sortKeyFieldNames;
338
+ var variables = {};
339
+ // TODO: process input
340
+ switch (operation) {
341
+ case 'CREATE':
342
+ variables = {
343
+ input: normalizeMutationInput(arg, modelDefinition, modelIntrospection),
344
+ };
345
+ break;
346
+ case 'UPDATE':
347
+ // readonly fields are not updated
348
+ variables = {
349
+ input: Object.fromEntries(Object.entries(normalizeMutationInput(arg, modelDefinition, modelIntrospection)).filter(function (_a) {
350
+ var _b = __read(_a, 1), fieldName = _b[0];
351
+ var isReadOnly = fields[fieldName].isReadOnly;
352
+ return !isReadOnly;
353
+ })),
354
+ };
355
+ break;
356
+ case 'READ':
357
+ case 'DELETE':
358
+ // only identifiers are sent
359
+ variables = isCustomPrimaryKey
360
+ ? __spreadArray([primaryKeyFieldName], __read(sortKeyFieldNames), false).reduce(function (acc, fieldName) {
361
+ acc[fieldName] = arg[fieldName];
362
+ return acc;
363
+ }, {})
364
+ : (_a = {}, _a[primaryKeyFieldName] = arg[primaryKeyFieldName], _a);
365
+ if (operation === 'DELETE') {
366
+ variables = { input: variables };
367
+ }
368
+ break;
369
+ case 'LIST':
370
+ case 'ONCREATE':
371
+ case 'ONUPDATE':
372
+ case 'ONDELETE':
373
+ if (arg === null || arg === void 0 ? void 0 : arg.filter) {
374
+ variables = { filter: arg.filter };
375
+ }
376
+ break;
377
+ default:
378
+ var exhaustiveCheck = operation;
379
+ throw new Error("Unhandled operation case: ".concat(exhaustiveCheck));
380
+ }
381
+ return variables;
382
+ }
383
+ /**
384
+ * Iterates over mutation input values and resolves any model inputs to their corresponding join fields/values
385
+ *
386
+ * @example
387
+ * ### Usage
388
+ * ```ts
389
+ * const result = normalizeMutationInput({ post: post }, model, modelDefinition);
390
+ * ```
391
+ * ### Result
392
+ * ```ts
393
+ * { postId: "abc123" }
394
+ * ```
395
+ *
396
+ */
397
+ export function normalizeMutationInput(mutationInput, model, modelDefinition) {
398
+ var fields = model.fields;
399
+ var normalized = {};
400
+ Object.entries(mutationInput).forEach(function (_a) {
401
+ var _b, _c, _d;
402
+ var _e = __read(_a, 2), inputFieldName = _e[0], inputValue = _e[1];
403
+ var relatedModelName = (_c = (_b = fields[inputFieldName]) === null || _b === void 0 ? void 0 : _b.type) === null || _c === void 0 ? void 0 : _c.model;
404
+ if (relatedModelName) {
405
+ var association_1 = (_d = fields[inputFieldName]) === null || _d === void 0 ? void 0 : _d.association;
406
+ var relatedModelDef = modelDefinition.models[relatedModelName];
407
+ var relatedModelPkInfo_1 = relatedModelDef.primaryKeyInfo;
408
+ if (association_1.connectionType === connectionType.HAS_ONE) {
409
+ association_1.targetNames.forEach(function (targetName, idx) {
410
+ var associatedFieldName = association_1.associatedWith[idx];
411
+ normalized[targetName] = inputValue[associatedFieldName];
412
+ });
413
+ }
414
+ if (association_1.connectionType === connectionType.BELONGS_TO) {
415
+ association_1.targetNames.forEach(function (targetName, idx) {
416
+ if (idx === 0) {
417
+ var associatedFieldName = relatedModelPkInfo_1.primaryKeyFieldName;
418
+ normalized[targetName] = inputValue[associatedFieldName];
419
+ }
420
+ else {
421
+ var associatedFieldName = relatedModelPkInfo_1.sortKeyFieldNames[idx - 1];
422
+ normalized[targetName] = inputValue[associatedFieldName];
423
+ }
424
+ });
425
+ }
426
+ }
427
+ else {
428
+ normalized[inputFieldName] = inputValue;
429
+ }
430
+ });
431
+ return normalized;
432
+ }
@@ -3,7 +3,7 @@ import { Observable } from 'rxjs';
3
3
  import { AmplifyClassV6 } from '@aws-amplify/core';
4
4
  import { CustomUserAgentDetails } from '@aws-amplify/core/internals/utils';
5
5
  import { GraphQLResult, GraphQLOperation, GraphQLOptions } from '../types';
6
- export declare const graphqlOperation: (query: any, variables?: {}, authToken?: string | undefined) => {
6
+ export declare const graphqlOperation: (query: any, variables?: {}, authToken?: string) => {
7
7
  query: any;
8
8
  variables: {};
9
9
  authToken: string | undefined;
@@ -37,7 +37,7 @@ export declare class InternalGraphQLAPIClass {
37
37
  * @param [additionalHeaders] - headers to merge in after any `graphql_headers` set in the config
38
38
  * @returns An Observable if the query is a subscription query, else a promise of the graphql result.
39
39
  */
40
- graphql<T = any>(amplify: AmplifyClassV6, { query: paramQuery, variables, authMode, authToken }: GraphQLOptions, additionalHeaders?: {
40
+ graphql<T = any>(amplify: AmplifyClassV6 | ((fn: (amplify: any) => Promise<any>) => Promise<AmplifyClassV6>), { query: paramQuery, variables, authMode, authToken }: GraphQLOptions, additionalHeaders?: {
41
41
  [key: string]: string;
42
42
  }, customUserAgentDetails?: CustomUserAgentDetails): Observable<GraphQLResult<T>> | Promise<GraphQLResult<T>>;
43
43
  private _graphql;
@@ -19,6 +19,12 @@ export var graphqlOperation = function (query, variables, authToken) {
19
19
  authToken: authToken,
20
20
  });
21
21
  };
22
+ var isAmplifyInstance = function (amplify) {
23
+ if (typeof amplify !== 'function') {
24
+ return true;
25
+ }
26
+ return false;
27
+ };
22
28
  /**
23
29
  * Export Cloud Logic APIs
24
30
  */
@@ -41,8 +47,8 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
41
47
  return 'InternalGraphQLAPI';
42
48
  };
43
49
  InternalGraphQLAPIClass.prototype._headerBasedAuth = function (amplify, authMode, additionalHeaders) {
44
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
45
50
  var _a;
51
+ if (additionalHeaders === void 0) { additionalHeaders = {}; }
46
52
  return __awaiter(this, void 0, void 0, function () {
47
53
  var config, _b, region, appSyncGraphqlEndpoint, apiKey, defaultAuthMode, authenticationType, headers, _c, session, token, e_1;
48
54
  return __generator(this, function (_d) {
@@ -127,6 +133,7 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
127
133
  * @returns An Observable if the query is a subscription query, else a promise of the graphql result.
128
134
  */
129
135
  InternalGraphQLAPIClass.prototype.graphql = function (amplify, _a, additionalHeaders, customUserAgentDetails) {
136
+ var _this = this;
130
137
  var paramQuery = _a.query, _b = _a.variables, variables = _b === void 0 ? {} : _b, authMode = _a.authMode, authToken = _a.authToken;
131
138
  var query = typeof paramQuery === 'string'
132
139
  ? parse(paramQuery)
@@ -141,14 +148,23 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
141
148
  switch (operationType) {
142
149
  case 'query':
143
150
  case 'mutation':
144
- var abortController = new AbortController();
145
- var responsePromise = this._graphql(amplify, { query: query, variables: variables, authMode: authMode }, headers, abortController, customUserAgentDetails);
146
- this._api.updateRequestToBeCancellable(responsePromise, abortController);
151
+ var abortController_1 = new AbortController();
152
+ var responsePromise = void 0;
153
+ if (isAmplifyInstance(amplify)) {
154
+ responsePromise = this._graphql(amplify, { query: query, variables: variables, authMode: authMode }, headers, abortController_1, customUserAgentDetails);
155
+ }
156
+ else {
157
+ var wrapper = function (amplifyInstance) {
158
+ return _this._graphql(amplifyInstance, { query: query, variables: variables, authMode: authMode }, headers, abortController_1, customUserAgentDetails);
159
+ };
160
+ responsePromise = amplify(wrapper);
161
+ }
162
+ this._api.updateRequestToBeCancellable(responsePromise, abortController_1);
147
163
  return responsePromise;
148
164
  case 'subscription':
149
165
  return this._graphqlSubscribe(amplify, { query: query, variables: variables, authMode: authMode }, headers, customUserAgentDetails);
150
166
  default:
151
- throw new Error("invalid operation type: " + operationType);
167
+ throw new Error("invalid operation type: ".concat(operationType));
152
168
  }
153
169
  };
154
170
  InternalGraphQLAPIClass.prototype._graphql = function (amplify, _a, additionalHeaders, abortController, customUserAgentDetails) {
@@ -0,0 +1,12 @@
1
+ import { V6Client } from '../types';
2
+ import { ClientGenerationParams } from './types';
3
+ /**
4
+ * @private
5
+ *
6
+ * Creates a client that can be used to make GraphQL requests, using a provided `AmplifyClassV6`
7
+ * compatible context object for config and auth fetching.
8
+ *
9
+ * @param params
10
+ * @returns
11
+ */
12
+ export declare function generateClient<T extends Record<any, any> = never>(params: ClientGenerationParams): V6Client<T>;
@@ -0,0 +1,26 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { graphql, cancel, isCancelError } from './v6';
4
+ import { generateModelsProperty } from './generateModelsProperty';
5
+ import { __amplify } from '../types';
6
+ /**
7
+ * @private
8
+ *
9
+ * Creates a client that can be used to make GraphQL requests, using a provided `AmplifyClassV6`
10
+ * compatible context object for config and auth fetching.
11
+ *
12
+ * @param params
13
+ * @returns
14
+ */
15
+ export function generateClient(params) {
16
+ var _a;
17
+ var client = (_a = {},
18
+ _a[__amplify] = params.amplify,
19
+ _a.graphql = graphql,
20
+ _a.cancel = cancel,
21
+ _a.isCancelError = isCancelError,
22
+ _a.models = {},
23
+ _a);
24
+ client.models = generateModelsProperty(client, params);
25
+ return client;
26
+ }
@@ -0,0 +1,4 @@
1
+ import { ModelTypes } from '@aws-amplify/amplify-api-next-types-alpha';
2
+ import { ClientGenerationParams } from './types';
3
+ import { V6Client } from '../types';
4
+ export declare function generateModelsProperty<T extends Record<any, any> = never>(client: V6Client, params: ClientGenerationParams): ModelTypes<T>;