@aws-amplify/api 5.4.5 → 5.4.6-api-v6-models.3f48fe3.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.
package/lib/API.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { AWSAppSyncRealTimeProvider } from '@aws-amplify/pubsub';
2
- import { GraphQLOptions, GraphQLResult } from '@aws-amplify/api-graphql';
2
+ import { GraphQLOptions, GraphQLResult, GraphQLQuery, GraphQLSubscription } from '@aws-amplify/api-graphql';
3
+ import { graphql as v6graphql } from '@aws-amplify/api-graphql/internals';
3
4
  import Observable from 'zen-observable-ts';
4
- import { GraphQLQuery, GraphQLSubscription } from './types';
5
5
  import { InternalAPIClass } from './internals/InternalAPI';
6
+ import type { ModelTypes } from '@aws-amplify/types-package-alpha';
6
7
  /**
7
8
  * @deprecated
8
9
  * Use RestApi or GraphQLAPI to reduce your application bundle size
@@ -23,5 +24,20 @@ export declare class APIClass extends InternalAPIClass {
23
24
  provider: AWSAppSyncRealTimeProvider;
24
25
  value: GraphQLResult<T>;
25
26
  }> : Promise<GraphQLResult<any>> | Observable<object>;
27
+ /**
28
+ * Generates an API client that can work with models or raw GraphQL
29
+ */
30
+ generateClient<T extends Record<any, any> = never>(): V6Client<T>;
26
31
  }
32
+ type FilteredKeys<T> = {
33
+ [P in keyof T]: T[P] extends never ? never : P;
34
+ }[keyof T];
35
+ type ExcludeNeverFields<O> = {
36
+ [K in FilteredKeys<O>]: O[K];
37
+ };
38
+ declare type V6Client<T extends Record<any, any> = never> = ExcludeNeverFields<{
39
+ graphql: typeof v6graphql;
40
+ models: ModelTypes<T>;
41
+ }>;
27
42
  export declare const API: APIClass;
43
+ export {};
package/lib/API.js CHANGED
@@ -1,8 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.API = exports.APIClass = void 0;
3
4
  var tslib_1 = require("tslib");
5
+ var internals_1 = require("@aws-amplify/api-graphql/internals");
4
6
  var core_1 = require("@aws-amplify/core");
5
7
  var InternalAPI_1 = require("./internals/InternalAPI");
8
+ var APIClient_1 = require("./APIClient");
6
9
  var logger = new core_1.ConsoleLogger('API');
7
10
  /**
8
11
  * @deprecated
@@ -20,9 +23,108 @@ var APIClass = /** @class */ (function (_super) {
20
23
  APIClass.prototype.graphql = function (options, additionalHeaders) {
21
24
  return _super.prototype.graphql.call(this, options, additionalHeaders);
22
25
  };
26
+ /**
27
+ * Generates an API client that can work with models or raw GraphQL
28
+ */
29
+ APIClass.prototype.generateClient = function () {
30
+ var e_1, _a;
31
+ var _this = this;
32
+ var config = _super.prototype.configure.call(this, {});
33
+ var modelIntrospection = config.modelIntrospection;
34
+ var client = {
35
+ graphql: internals_1.graphql,
36
+ models: {},
37
+ };
38
+ var _loop_1 = function (model) {
39
+ var name_1 = model.name;
40
+ client.models[name_1] = {};
41
+ Object.entries(APIClient_1.graphQLOperationsInfo).forEach(function (_a) {
42
+ var _b = tslib_1.__read(_a, 2), key = _b[0], operationPrefix = _b[1].operationPrefix;
43
+ var operation = key;
44
+ if (operation === 'LIST') {
45
+ client.models[name_1][operationPrefix] = function (args) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
46
+ var query, variables, res, _a, key_1, flattenedResult, initialized;
47
+ return tslib_1.__generator(this, function (_b) {
48
+ switch (_b.label) {
49
+ case 0:
50
+ query = (0, APIClient_1.generateGraphQLDocument)(modelIntrospection.models, name_1, 'LIST', args);
51
+ variables = (0, APIClient_1.buildGraphQLVariables)(model, 'LIST', args, modelIntrospection);
52
+ console.log('API list', query, variables);
53
+ return [4 /*yield*/, this.graphql({
54
+ query: query,
55
+ variables: variables,
56
+ })];
57
+ case 1:
58
+ res = (_b.sent());
59
+ // flatten response
60
+ if (res.data !== undefined) {
61
+ _a = tslib_1.__read(Object.keys(res.data), 1), key_1 = _a[0];
62
+ if (res.data[key_1].items) {
63
+ flattenedResult = res.data[key_1].items;
64
+ // don't init if custom selection set
65
+ if (args === null || args === void 0 ? void 0 : args.selectionSet) {
66
+ return [2 /*return*/, flattenedResult];
67
+ }
68
+ else {
69
+ initialized = (0, APIClient_1.initializeModel)(client, name_1, flattenedResult, modelIntrospection);
70
+ console.log('initialized', initialized);
71
+ return [2 /*return*/, initialized];
72
+ }
73
+ }
74
+ return [2 /*return*/, res.data[key_1]];
75
+ }
76
+ return [2 /*return*/, res];
77
+ }
78
+ });
79
+ }); };
80
+ }
81
+ else {
82
+ client.models[name_1][operationPrefix] = function (arg, options) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
83
+ var query, variables, res, _a, key_2, _b, initialized;
84
+ return tslib_1.__generator(this, function (_c) {
85
+ switch (_c.label) {
86
+ case 0:
87
+ query = (0, APIClient_1.generateGraphQLDocument)(modelIntrospection.models, name_1, operation);
88
+ variables = (0, APIClient_1.buildGraphQLVariables)(model, operation, arg, modelIntrospection);
89
+ console.log("API ".concat(operationPrefix), query, variables);
90
+ return [4 /*yield*/, this.graphql({
91
+ query: query,
92
+ variables: variables,
93
+ })];
94
+ case 1:
95
+ res = (_c.sent());
96
+ // flatten response
97
+ if (res.data !== undefined) {
98
+ _a = tslib_1.__read(Object.keys(res.data), 1), key_2 = _a[0];
99
+ _b = tslib_1.__read((0, APIClient_1.initializeModel)(client, name_1, [res.data[key_2]], modelIntrospection), 1), initialized = _b[0];
100
+ return [2 /*return*/, initialized];
101
+ }
102
+ return [2 /*return*/, res];
103
+ }
104
+ });
105
+ }); };
106
+ }
107
+ });
108
+ };
109
+ try {
110
+ // TODO: refactor this to use separate methods for each CRUDL.
111
+ // Doesn't make sense to gen the methods dynamically given the different args and return values
112
+ for (var _b = tslib_1.__values(Object.values(modelIntrospection.models)), _c = _b.next(); !_c.done; _c = _b.next()) {
113
+ var model = _c.value;
114
+ _loop_1(model);
115
+ }
116
+ }
117
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
118
+ finally {
119
+ try {
120
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
121
+ }
122
+ finally { if (e_1) throw e_1.error; }
123
+ }
124
+ return client;
125
+ };
23
126
  return APIClass;
24
127
  }(InternalAPI_1.InternalAPIClass));
25
128
  exports.APIClass = APIClass;
26
129
  exports.API = new APIClass(null);
27
130
  core_1.Amplify.register(exports.API);
28
- //# sourceMappingURL=API.js.map
@@ -0,0 +1,46 @@
1
+ type ListArgs = {
2
+ selectionSet?: string[];
3
+ filter?: {};
4
+ };
5
+ export declare function initializeModel(client: any, modelName: string, result: any[], modelIntrospection: any): any[];
6
+ export declare const graphQLOperationsInfo: {
7
+ CREATE: {
8
+ operationPrefix: "create";
9
+ usePlural: boolean;
10
+ };
11
+ READ: {
12
+ operationPrefix: "get";
13
+ usePlural: boolean;
14
+ };
15
+ UPDATE: {
16
+ operationPrefix: "update";
17
+ usePlural: boolean;
18
+ };
19
+ DELETE: {
20
+ operationPrefix: "delete";
21
+ usePlural: boolean;
22
+ };
23
+ LIST: {
24
+ operationPrefix: "list";
25
+ usePlural: boolean;
26
+ };
27
+ };
28
+ export type ModelOperation = keyof typeof graphQLOperationsInfo;
29
+ export declare function generateGraphQLDocument(modelIntrospection: any, modelName: string, modelOperation: ModelOperation, listArgs?: ListArgs): string;
30
+ export declare function buildGraphQLVariables(modelDefinition: any, operation: ModelOperation, arg: any, modelIntrospection: any): object;
31
+ /**
32
+ * Iterates over mutation input values and resolves any model inputs to their corresponding join fields/values
33
+ *
34
+ * @example
35
+ * ### Usage
36
+ * ```ts
37
+ * const result = normalizeMutationInput({ post: post }, model, modelDefinition);
38
+ * ```
39
+ * ### Result
40
+ * ```ts
41
+ * { postId: "abc123" }
42
+ * ```
43
+ *
44
+ */
45
+ export declare function normalizeMutationInput(mutationInput: any, model: any, modelDefinition: any): Record<string, unknown>;
46
+ export {};
@@ -0,0 +1,336 @@
1
+ "use strict";
2
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.normalizeMutationInput = exports.buildGraphQLVariables = exports.generateGraphQLDocument = exports.graphQLOperationsInfo = exports.initializeModel = void 0;
6
+ var tslib_1 = require("tslib");
7
+ var connectionType = {
8
+ HAS_ONE: 'HAS_ONE',
9
+ HAS_MANY: 'HAS_MANY',
10
+ BELONGS_TO: 'BELONGS_TO',
11
+ };
12
+ // TODO: this should accept single result to support CRUD methods; create helper for array/list
13
+ function initializeModel(client, modelName, result, modelIntrospection) {
14
+ var introModel = modelIntrospection.models[modelName];
15
+ var introModelFields = introModel.fields;
16
+ var modelFields = Object.entries(introModelFields)
17
+ .filter(function (_a) {
18
+ var _b;
19
+ var _c = tslib_1.__read(_a, 2), _ = _c[0], field = _c[1];
20
+ return ((_b = field === null || field === void 0 ? void 0 : field.type) === null || _b === void 0 ? void 0 : _b.model) !== undefined;
21
+ })
22
+ .map(function (_a) {
23
+ var _b = tslib_1.__read(_a, 1), fieldName = _b[0];
24
+ return fieldName;
25
+ });
26
+ return result.map(function (record) {
27
+ var e_1, _a;
28
+ var _b, _c;
29
+ var initializedRelationalFields = {};
30
+ var _loop_1 = function (field) {
31
+ var relatedModelName = introModelFields[field].type.model;
32
+ var relatedModel = modelIntrospection.models[relatedModelName];
33
+ var relatedModelPKFieldName = relatedModel.primaryKeyInfo.primaryKeyFieldName;
34
+ var relatedModelSKFieldNames = relatedModel.primaryKeyInfo.sortKeyFieldNames;
35
+ var relationType = introModelFields[field].association.connectionType;
36
+ var connectionFields = introModelFields[field].association.associatedWith;
37
+ var targetNames = ((_b = introModelFields[field].association) === null || _b === void 0 ? void 0 : _b.targetNames) || [];
38
+ switch (relationType) {
39
+ case connectionType.HAS_ONE:
40
+ case connectionType.BELONGS_TO:
41
+ var sortKeyValues_1 = relatedModelSKFieldNames.reduce(function (acc, curVal) {
42
+ if (record[curVal]) {
43
+ return (acc[curVal] = record[curVal]);
44
+ }
45
+ }, {});
46
+ initializedRelationalFields[field] = function () {
47
+ var _a;
48
+ if (record[targetNames[0]]) {
49
+ return client.models[relatedModelName].get(tslib_1.__assign((_a = {}, _a[relatedModelPKFieldName] = record[targetNames[0]], _a), sortKeyValues_1));
50
+ }
51
+ return undefined;
52
+ };
53
+ break;
54
+ case connectionType.HAS_MANY:
55
+ var parentPk_1 = introModel.primaryKeyInfo.primaryKeyFieldName;
56
+ var parentSK_1 = introModel.primaryKeyInfo.sortKeyFieldNames;
57
+ // M:N check - TODO: refactor
58
+ if ((_c = relatedModel.fields[connectionFields[0]]) === null || _c === void 0 ? void 0 : _c.type.model) {
59
+ var relatedTargetNames = relatedModel.fields[connectionFields[0]].association.targetNames;
60
+ var hasManyFilter_1 = relatedTargetNames.map(function (field, idx) {
61
+ var _a, _b;
62
+ if (idx === 0) {
63
+ return _a = {}, _a[field] = { eq: record[parentPk_1] }, _a;
64
+ }
65
+ return _b = {}, _b[field] = { eq: record[parentSK_1[idx - 1]] }, _b;
66
+ });
67
+ initializedRelationalFields[field] = function () {
68
+ if (record[parentPk_1]) {
69
+ return client.models[relatedModelName].list({
70
+ filter: { and: hasManyFilter_1 },
71
+ });
72
+ }
73
+ return [];
74
+ };
75
+ break;
76
+ }
77
+ var hasManyFilter_2 = connectionFields.map(function (field, idx) {
78
+ var _a, _b;
79
+ if (idx === 0) {
80
+ return _a = {}, _a[field] = { eq: record[parentPk_1] }, _a;
81
+ }
82
+ return _b = {}, _b[field] = { eq: record[parentSK_1[idx - 1]] }, _b;
83
+ });
84
+ initializedRelationalFields[field] = function () {
85
+ if (record[parentPk_1]) {
86
+ return client.models[relatedModelName].list({
87
+ filter: { and: hasManyFilter_2 },
88
+ });
89
+ }
90
+ return [];
91
+ };
92
+ break;
93
+ default:
94
+ break;
95
+ }
96
+ };
97
+ try {
98
+ for (var modelFields_1 = tslib_1.__values(modelFields), modelFields_1_1 = modelFields_1.next(); !modelFields_1_1.done; modelFields_1_1 = modelFields_1.next()) {
99
+ var field = modelFields_1_1.value;
100
+ _loop_1(field);
101
+ }
102
+ }
103
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
104
+ finally {
105
+ try {
106
+ if (modelFields_1_1 && !modelFields_1_1.done && (_a = modelFields_1.return)) _a.call(modelFields_1);
107
+ }
108
+ finally { if (e_1) throw e_1.error; }
109
+ }
110
+ return tslib_1.__assign(tslib_1.__assign({}, record), initializedRelationalFields);
111
+ });
112
+ }
113
+ exports.initializeModel = initializeModel;
114
+ exports.graphQLOperationsInfo = {
115
+ CREATE: { operationPrefix: 'create', usePlural: false },
116
+ READ: { operationPrefix: 'get', usePlural: false },
117
+ UPDATE: { operationPrefix: 'update', usePlural: false },
118
+ DELETE: { operationPrefix: 'delete', usePlural: false },
119
+ LIST: { operationPrefix: 'list', usePlural: true },
120
+ };
121
+ var graphQLDocumentsCache = new Map();
122
+ var SELECTION_SET_ALL_NESTED = '*';
123
+ function defaultSelectionSetForModel(modelDefinition) {
124
+ var fields = modelDefinition.fields;
125
+ return Object.values(fields)
126
+ .map(function (_a) {
127
+ var type = _a.type, name = _a.name;
128
+ return typeof type === 'string' && name;
129
+ }) // Default selection set omits model fields
130
+ .filter(Boolean)
131
+ .join(' ');
132
+ }
133
+ function generateSelectionSet(modelIntrospection, modelName, selectionSet) {
134
+ var e_2, _a;
135
+ var _b, _c, _d;
136
+ var modelDefinition = modelIntrospection[modelName];
137
+ var fields = modelDefinition.fields;
138
+ if (!selectionSet) {
139
+ return defaultSelectionSetForModel(modelDefinition);
140
+ }
141
+ var selSet = [];
142
+ try {
143
+ for (var selectionSet_1 = tslib_1.__values(selectionSet), selectionSet_1_1 = selectionSet_1.next(); !selectionSet_1_1.done; selectionSet_1_1 = selectionSet_1.next()) {
144
+ var f = selectionSet_1_1.value;
145
+ var nested = f.includes('.');
146
+ if (nested) {
147
+ var _e = tslib_1.__read(f.split('.'), 2), modelFieldName = _e[0], selectedField = _e[1];
148
+ var relatedModel = (_c = (_b = fields[modelFieldName]) === null || _b === void 0 ? void 0 : _b.type) === null || _c === void 0 ? void 0 : _c.model;
149
+ if (!relatedModel) {
150
+ // TODO: may need to change this to support custom types
151
+ throw Error("".concat(modelFieldName, " is not a model field"));
152
+ }
153
+ if (selectedField === SELECTION_SET_ALL_NESTED) {
154
+ var relatedModelDefinition = modelIntrospection[relatedModel];
155
+ var defaultSelectionSet = defaultSelectionSetForModel(relatedModelDefinition);
156
+ if ((_d = fields[modelFieldName]) === null || _d === void 0 ? void 0 : _d.isArray) {
157
+ selSet.push("".concat(modelFieldName, " { items { ").concat(defaultSelectionSet, " } }"));
158
+ }
159
+ else {
160
+ selSet.push("".concat(modelFieldName, " { ").concat(defaultSelectionSet, " }"));
161
+ }
162
+ }
163
+ }
164
+ else {
165
+ var exists = Boolean(fields[f]);
166
+ if (!exists) {
167
+ throw Error("".concat(f, " is not a field of model ").concat(modelName));
168
+ }
169
+ selSet.push(f);
170
+ }
171
+ }
172
+ }
173
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
174
+ finally {
175
+ try {
176
+ if (selectionSet_1_1 && !selectionSet_1_1.done && (_a = selectionSet_1.return)) _a.call(selectionSet_1);
177
+ }
178
+ finally { if (e_2) throw e_2.error; }
179
+ }
180
+ return selSet.join(' ');
181
+ }
182
+ function generateGraphQLDocument(modelIntrospection, modelName, modelOperation, listArgs) {
183
+ var _a;
184
+ var _b, _c;
185
+ var modelDefinition = modelIntrospection[modelName];
186
+ var name = modelDefinition.name, pluralName = modelDefinition.pluralName, fields = modelDefinition.fields, _d = modelDefinition.primaryKeyInfo, isCustomPrimaryKey = _d.isCustomPrimaryKey, primaryKeyFieldName = _d.primaryKeyFieldName, sortKeyFieldNames = _d.sortKeyFieldNames;
187
+ var _e = exports.graphQLOperationsInfo[modelOperation], operationPrefix = _e.operationPrefix, usePlural = _e.usePlural;
188
+ var selectionSet = (listArgs || {}).selectionSet;
189
+ var fromCache = (_b = graphQLDocumentsCache.get(name)) === null || _b === void 0 ? void 0 : _b.get(modelOperation);
190
+ if (fromCache !== undefined) {
191
+ return fromCache;
192
+ }
193
+ if (!graphQLDocumentsCache.has(name)) {
194
+ graphQLDocumentsCache.set(name, new Map());
195
+ }
196
+ var graphQLFieldName = "".concat(operationPrefix).concat(usePlural ? pluralName : name);
197
+ var graphQLOperationType;
198
+ var graphQLSelectionSet;
199
+ var graphQLArguments;
200
+ var selectionSetFields = generateSelectionSet(modelIntrospection, modelName, selectionSet);
201
+ console.log('generated sel set', selectionSetFields);
202
+ switch (modelOperation) {
203
+ case 'CREATE':
204
+ case 'UPDATE':
205
+ case 'DELETE':
206
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = {
207
+ input: "".concat(operationPrefix.charAt(0).toLocaleUpperCase() +
208
+ operationPrefix.slice(1)).concat(name, "Input!"),
209
+ });
210
+ graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'mutation');
211
+ case 'READ':
212
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = isCustomPrimaryKey
213
+ ? tslib_1.__spreadArray([primaryKeyFieldName], tslib_1.__read(sortKeyFieldNames), false).reduce(function (acc, fieldName) {
214
+ acc[fieldName] = fields[fieldName].type;
215
+ return acc;
216
+ }, {})
217
+ : (_a = {},
218
+ _a[primaryKeyFieldName] = "".concat(fields[primaryKeyFieldName].type, "!"),
219
+ _a));
220
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = selectionSetFields);
221
+ case 'LIST':
222
+ graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = {
223
+ filter: "Model".concat(name, "FilterInput"),
224
+ });
225
+ graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'query');
226
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = "items { ".concat(selectionSetFields, " }"));
227
+ }
228
+ var graphQLDocument = "".concat(graphQLOperationType).concat(graphQLArguments
229
+ ? "(".concat(Object.entries(graphQLArguments).map(function (_a) {
230
+ var _b = tslib_1.__read(_a, 2), fieldName = _b[0], type = _b[1];
231
+ return "$".concat(fieldName, ": ").concat(type);
232
+ }), ")")
233
+ : '', " { ").concat(graphQLFieldName).concat(graphQLArguments
234
+ ? "(".concat(Object.keys(graphQLArguments).map(function (fieldName) { return "".concat(fieldName, ": $").concat(fieldName); }), ")")
235
+ : '', " { ").concat(graphQLSelectionSet, " } }");
236
+ (_c = graphQLDocumentsCache.get(name)) === null || _c === void 0 ? void 0 : _c.set(modelOperation, graphQLDocument);
237
+ return graphQLDocument;
238
+ }
239
+ exports.generateGraphQLDocument = generateGraphQLDocument;
240
+ function buildGraphQLVariables(modelDefinition, operation, arg, modelIntrospection) {
241
+ var _a;
242
+ var fields = modelDefinition.fields, _b = modelDefinition.primaryKeyInfo, isCustomPrimaryKey = _b.isCustomPrimaryKey, primaryKeyFieldName = _b.primaryKeyFieldName, sortKeyFieldNames = _b.sortKeyFieldNames;
243
+ var variables = {};
244
+ // TODO: process input
245
+ switch (operation) {
246
+ case 'CREATE':
247
+ variables = {
248
+ input: normalizeMutationInput(arg, modelDefinition, modelIntrospection),
249
+ };
250
+ break;
251
+ case 'UPDATE':
252
+ // readonly fields are not updated
253
+ variables = {
254
+ input: Object.fromEntries(Object.entries(normalizeMutationInput(arg, modelDefinition, modelIntrospection)).filter(function (_a) {
255
+ var _b = tslib_1.__read(_a, 1), fieldName = _b[0];
256
+ var isReadOnly = fields[fieldName].isReadOnly;
257
+ return !isReadOnly;
258
+ })),
259
+ };
260
+ break;
261
+ case 'READ':
262
+ case 'DELETE':
263
+ // only identifiers are sent
264
+ variables = isCustomPrimaryKey
265
+ ? tslib_1.__spreadArray([primaryKeyFieldName], tslib_1.__read(sortKeyFieldNames), false).reduce(function (acc, fieldName) {
266
+ acc[fieldName] = arg[fieldName];
267
+ return acc;
268
+ }, {})
269
+ : (_a = {}, _a[primaryKeyFieldName] = arg[primaryKeyFieldName], _a);
270
+ if (operation === 'DELETE') {
271
+ variables = { input: variables };
272
+ }
273
+ break;
274
+ case 'LIST':
275
+ if (arg === null || arg === void 0 ? void 0 : arg.filter) {
276
+ variables = { filter: arg.filter };
277
+ }
278
+ break;
279
+ default:
280
+ var exhaustiveCheck = operation;
281
+ throw new Error("Unhandled operation case: ".concat(exhaustiveCheck));
282
+ }
283
+ return variables;
284
+ }
285
+ exports.buildGraphQLVariables = buildGraphQLVariables;
286
+ /**
287
+ * Iterates over mutation input values and resolves any model inputs to their corresponding join fields/values
288
+ *
289
+ * @example
290
+ * ### Usage
291
+ * ```ts
292
+ * const result = normalizeMutationInput({ post: post }, model, modelDefinition);
293
+ * ```
294
+ * ### Result
295
+ * ```ts
296
+ * { postId: "abc123" }
297
+ * ```
298
+ *
299
+ */
300
+ function normalizeMutationInput(mutationInput, model, modelDefinition) {
301
+ var fields = model.fields;
302
+ var normalized = {};
303
+ Object.entries(mutationInput).forEach(function (_a) {
304
+ var _b, _c, _d;
305
+ var _e = tslib_1.__read(_a, 2), inputFieldName = _e[0], inputValue = _e[1];
306
+ var relatedModelName = (_c = (_b = fields[inputFieldName]) === null || _b === void 0 ? void 0 : _b.type) === null || _c === void 0 ? void 0 : _c.model;
307
+ if (relatedModelName) {
308
+ var association_1 = (_d = fields[inputFieldName]) === null || _d === void 0 ? void 0 : _d.association;
309
+ var relatedModelDef = modelDefinition.models[relatedModelName];
310
+ var relatedModelPkInfo_1 = relatedModelDef.primaryKeyInfo;
311
+ if (association_1.connectionType === connectionType.HAS_ONE) {
312
+ association_1.targetNames.forEach(function (targetName, idx) {
313
+ var associatedFieldName = association_1.associatedWith[idx];
314
+ normalized[targetName] = inputValue[associatedFieldName];
315
+ });
316
+ }
317
+ if (association_1.connectionType === connectionType.BELONGS_TO) {
318
+ association_1.targetNames.forEach(function (targetName, idx) {
319
+ if (idx === 0) {
320
+ var associatedFieldName = relatedModelPkInfo_1.primaryKeyFieldName;
321
+ normalized[targetName] = inputValue[associatedFieldName];
322
+ }
323
+ else {
324
+ var associatedFieldName = relatedModelPkInfo_1.sortKeyFieldNames[idx - 1];
325
+ normalized[targetName] = inputValue[associatedFieldName];
326
+ }
327
+ });
328
+ }
329
+ }
330
+ else {
331
+ normalized[inputFieldName] = inputValue;
332
+ }
333
+ });
334
+ return normalized;
335
+ }
336
+ exports.normalizeMutationInput = normalizeMutationInput;
package/lib/index.js CHANGED
@@ -2,11 +2,11 @@
2
2
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.GRAPHQL_AUTH_MODE = exports.GraphQLAuthError = exports.graphqlOperation = exports.APIClass = exports.API = void 0;
5
6
  var API_1 = require("./API");
6
- exports.API = API_1.API;
7
- exports.APIClass = API_1.APIClass;
7
+ Object.defineProperty(exports, "API", { enumerable: true, get: function () { return API_1.API; } });
8
+ Object.defineProperty(exports, "APIClass", { enumerable: true, get: function () { return API_1.APIClass; } });
8
9
  var api_graphql_1 = require("@aws-amplify/api-graphql");
9
- exports.graphqlOperation = api_graphql_1.graphqlOperation;
10
- exports.GraphQLAuthError = api_graphql_1.GraphQLAuthError;
11
- exports.GRAPHQL_AUTH_MODE = api_graphql_1.GRAPHQL_AUTH_MODE;
12
- //# sourceMappingURL=index.js.map
10
+ Object.defineProperty(exports, "graphqlOperation", { enumerable: true, get: function () { return api_graphql_1.graphqlOperation; } });
11
+ Object.defineProperty(exports, "GraphQLAuthError", { enumerable: true, get: function () { return api_graphql_1.GraphQLAuthError; } });
12
+ Object.defineProperty(exports, "GRAPHQL_AUTH_MODE", { enumerable: true, get: function () { return api_graphql_1.GRAPHQL_AUTH_MODE; } });
@@ -1,8 +1,7 @@
1
- import { GraphQLOperation, GraphQLOptions, GraphQLResult, OperationTypeNode } from '@aws-amplify/api-graphql';
1
+ import { GraphQLOperation, GraphQLOptions, GraphQLResult, OperationTypeNode, GraphQLQuery, GraphQLSubscription } from '@aws-amplify/api-graphql';
2
2
  import { CustomUserAgentDetails } from '@aws-amplify/core';
3
3
  import { AWSAppSyncRealTimeProvider } from '@aws-amplify/pubsub';
4
4
  import Observable from 'zen-observable-ts';
5
- import { GraphQLQuery, GraphQLSubscription } from '../types';
6
5
  /**
7
6
  * @deprecated
8
7
  * Use RestApi or GraphQLAPI to reduce your application bundle size
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InternalAPI = exports.InternalAPIClass = void 0;
3
4
  var tslib_1 = require("tslib");
4
5
  var internals_1 = require("@aws-amplify/api-graphql/internals");
5
6
  var api_rest_1 = require("@aws-amplify/api-rest");
@@ -164,4 +165,3 @@ var InternalAPIClass = /** @class */ (function () {
164
165
  exports.InternalAPIClass = InternalAPIClass;
165
166
  exports.InternalAPI = new InternalAPIClass(null);
166
167
  core_1.Amplify.register(exports.InternalAPI);
167
- //# sourceMappingURL=InternalAPI.js.map
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InternalAPIClass = exports.InternalAPI = void 0;
3
4
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4
5
  // SPDX-License-Identifier: Apache-2.0
5
6
  var InternalAPI_1 = require("./InternalAPI");
6
- exports.InternalAPI = InternalAPI_1.InternalAPI;
7
- exports.InternalAPIClass = InternalAPI_1.InternalAPIClass;
8
- //# sourceMappingURL=index.js.map
7
+ Object.defineProperty(exports, "InternalAPI", { enumerable: true, get: function () { return InternalAPI_1.InternalAPI; } });
8
+ Object.defineProperty(exports, "InternalAPIClass", { enumerable: true, get: function () { return InternalAPI_1.InternalAPIClass; } });