@aws-amplify/api-graphql 4.0.1-api-v6-models.3eb7748.0 → 4.0.1-api-v6-models.01b2bb8.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.
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Iterates through a collection to find a matching item and returns the index.
3
+ *
4
+ * @param needle The item to search for
5
+ * @param haystack The collection to search
6
+ * @param keyFields The fields used to indicate a match
7
+ * @returns Index of `needle` in `haystack`, otherwise -1 if not found.
8
+ */
9
+ export declare function findIndexByFields<T>(needle: T, haystack: T[], keyFields: Array<keyof T>): number;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findIndexByFields = void 0;
4
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ // SPDX-License-Identifier: Apache-2.0
6
+ /**
7
+ * Iterates through a collection to find a matching item and returns the index.
8
+ *
9
+ * @param needle The item to search for
10
+ * @param haystack The collection to search
11
+ * @param keyFields The fields used to indicate a match
12
+ * @returns Index of `needle` in `haystack`, otherwise -1 if not found.
13
+ */
14
+ function findIndexByFields(needle, haystack, keyFields) {
15
+ var searchObject = Object.fromEntries(keyFields.map(function (fieldName) { return [fieldName, needle[fieldName]]; }));
16
+ var _loop_1 = function (i) {
17
+ if (Object.keys(searchObject).every(function (k) { return searchObject[k] === haystack[i][k]; })) {
18
+ return { value: i };
19
+ }
20
+ };
21
+ for (var i = 0; i < haystack.length; i++) {
22
+ var state_1 = _loop_1(i);
23
+ if (typeof state_1 === "object")
24
+ return state_1.value;
25
+ }
26
+ return -1;
27
+ }
28
+ exports.findIndexByFields = findIndexByFields;
@@ -1,2 +1,4 @@
1
1
  export { resolveConfig } from './resolveConfig';
2
2
  export { resolveLibraryOptions } from './resolveLibraryOptions';
3
+ export { resolvePKFields } from './resolvePKFields';
4
+ export { findIndexByFields } from './findIndexByFields';
@@ -2,8 +2,12 @@
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.resolveLibraryOptions = exports.resolveConfig = void 0;
5
+ exports.findIndexByFields = exports.resolvePKFields = exports.resolveLibraryOptions = exports.resolveConfig = void 0;
6
6
  var resolveConfig_1 = require("./resolveConfig");
7
7
  Object.defineProperty(exports, "resolveConfig", { enumerable: true, get: function () { return resolveConfig_1.resolveConfig; } });
8
8
  var resolveLibraryOptions_1 = require("./resolveLibraryOptions");
9
9
  Object.defineProperty(exports, "resolveLibraryOptions", { enumerable: true, get: function () { return resolveLibraryOptions_1.resolveLibraryOptions; } });
10
+ var resolvePKFields_1 = require("./resolvePKFields");
11
+ Object.defineProperty(exports, "resolvePKFields", { enumerable: true, get: function () { return resolvePKFields_1.resolvePKFields; } });
12
+ var findIndexByFields_1 = require("./findIndexByFields");
13
+ Object.defineProperty(exports, "findIndexByFields", { enumerable: true, get: function () { return findIndexByFields_1.findIndexByFields; } });
@@ -0,0 +1,13 @@
1
+ import { ResourcesConfig } from '@aws-amplify/core';
2
+ type GraphQLConfig = Exclude<ResourcesConfig['API'], undefined>['GraphQL'];
3
+ type ModelIntrospectionSchema = Exclude<Exclude<GraphQLConfig, undefined>['modelIntrospection'], undefined>;
4
+ type SchemaModel = ModelIntrospectionSchema['models'][string];
5
+ /**
6
+ * Given a SchemaModel from a ModelIntrospectionSchema, returns the primary key
7
+ * as an array of field names.
8
+ *
9
+ * @param model The model object
10
+ * @returns Array of field names
11
+ */
12
+ export declare function resolvePKFields(model: SchemaModel): string[];
13
+ export {};
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolvePKFields = void 0;
4
+ var tslib_1 = require("tslib");
5
+ /**
6
+ * Given a SchemaModel from a ModelIntrospectionSchema, returns the primary key
7
+ * as an array of field names.
8
+ *
9
+ * @param model The model object
10
+ * @returns Array of field names
11
+ */
12
+ function resolvePKFields(model) {
13
+ var _a = model.primaryKeyInfo, primaryKeyFieldName = _a.primaryKeyFieldName, sortKeyFieldNames = _a.sortKeyFieldNames;
14
+ return tslib_1.__spreadArray([primaryKeyFieldName], tslib_1.__read(sortKeyFieldNames), false);
15
+ }
16
+ exports.resolvePKFields = resolvePKFields;
@@ -42,6 +42,10 @@ export declare const graphQLOperationsInfo: {
42
42
  operationPrefix: "onDelete";
43
43
  usePlural: boolean;
44
44
  };
45
+ OBSERVE_QUERY: {
46
+ operationPrefix: "observeQuery";
47
+ usePlural: boolean;
48
+ };
45
49
  };
46
50
  export type ModelOperation = keyof typeof graphQLOperationsInfo;
47
51
  /**
@@ -140,9 +140,10 @@ export var graphQLOperationsInfo = {
140
140
  ONCREATE: { operationPrefix: 'onCreate', usePlural: false },
141
141
  ONUPDATE: { operationPrefix: 'onUpdate', usePlural: false },
142
142
  ONDELETE: { operationPrefix: 'onDelete', usePlural: false },
143
+ OBSERVE_QUERY: { operationPrefix: 'observeQuery', usePlural: false },
143
144
  };
144
145
  var graphQLDocumentsCache = new Map();
145
- var SELECTION_SET_ALL_NESTED = '*';
146
+ var SELECTION_SET_WILDCARD = '*';
146
147
  function defaultSelectionSetForModel(modelDefinition) {
147
148
  // fields that are explicitly part of the graphql schema; not
148
149
  // inferred from owner auth rules.
@@ -179,70 +180,53 @@ var FIELD_IR = '';
179
180
  * ```
180
181
  */
181
182
  export function customSelectionSetToIR(modelIntrospection, modelName, selectionSet) {
182
- var e_2, _a;
183
- var _b, _c, _d, _e;
184
183
  var modelDefinition = modelIntrospection[modelName];
185
- var fields = modelDefinition.fields;
186
- var intermediateSelectionSet = {};
187
- try {
188
- for (var selectionSet_1 = __values(selectionSet), selectionSet_1_1 = selectionSet_1.next(); !selectionSet_1_1.done; selectionSet_1_1 = selectionSet_1.next()) {
189
- var f = selectionSet_1_1.value;
190
- var nested = f.includes('.');
191
- if (nested) {
192
- var _f = __read(f.split('.'), 2), modelFieldName = _f[0], selectedField = _f[1];
193
- var relatedModel = (_c = (_b = fields[modelFieldName]) === null || _b === void 0 ? void 0 : _b.type) === null || _c === void 0 ? void 0 : _c.model;
194
- if (!relatedModel) {
195
- // TODO: may need to change this to support custom types
196
- throw Error("".concat(modelFieldName, " is not a model field"));
197
- }
198
- if (selectedField === SELECTION_SET_ALL_NESTED) {
199
- var relatedModelDefinition = modelIntrospection[relatedModel];
200
- var defaultSelectionSet = defaultSelectionSetForModel(relatedModelDefinition);
201
- var reduced = defaultSelectionSet.reduce(function (acc, curVal) {
202
- acc[curVal] = FIELD_IR;
203
- return acc;
204
- }, {});
205
- if ((_d = fields[modelFieldName]) === null || _d === void 0 ? void 0 : _d.isArray) {
206
- intermediateSelectionSet[modelFieldName] = {
207
- items: reduced,
208
- };
209
- }
210
- else {
211
- intermediateSelectionSet[modelFieldName] = reduced;
212
- }
213
- }
214
- else {
215
- var getNestedSelSet = customSelectionSetToIR(modelIntrospection, relatedModel, [selectedField]);
216
- if ((_e = fields[modelFieldName]) === null || _e === void 0 ? void 0 : _e.isArray) {
217
- var existing = intermediateSelectionSet[modelFieldName] || { items: {} };
218
- var merged = __assign(__assign({}, existing.items), getNestedSelSet);
219
- intermediateSelectionSet[modelFieldName] = { items: merged };
220
- }
221
- else {
222
- var existingItems = intermediateSelectionSet[modelFieldName] || {};
223
- var merged = __assign(__assign({}, existingItems), getNestedSelSet);
224
- intermediateSelectionSet[modelFieldName] = merged;
225
- }
226
- }
184
+ var modelFields = modelDefinition.fields;
185
+ return selectionSet.reduce(function (resultObj, path) {
186
+ var _a, _b, _c;
187
+ var _d = __read(path.split('.')), fieldName = _d[0], nested = _d[1], rest = _d.slice(2);
188
+ if (nested) {
189
+ var relatedModel = (_b = (_a = modelFields[fieldName]) === null || _a === void 0 ? void 0 : _a.type) === null || _b === void 0 ? void 0 : _b.model;
190
+ if (!relatedModel) {
191
+ // TODO: may need to change this to support custom types
192
+ throw Error("".concat(fieldName, " is not a model field"));
227
193
  }
228
- else {
229
- var exists = Boolean(fields[f]);
230
- if (!exists) {
231
- throw Error("".concat(f, " is not a field of model ").concat(modelName));
232
- }
233
- intermediateSelectionSet[f] = FIELD_IR;
194
+ var relatedModelDefinition = modelIntrospection[relatedModel];
195
+ var selectionSet_1 = nested === SELECTION_SET_WILDCARD
196
+ ? defaultSelectionSetIR(relatedModelDefinition)
197
+ : // if we have a path like 'field.anotherField' recursively build up selection set IR
198
+ customSelectionSetToIR(modelIntrospection, relatedModel, [
199
+ __spreadArray([nested], __read(rest), false).join('.'),
200
+ ]);
201
+ if ((_c = modelFields[fieldName]) === null || _c === void 0 ? void 0 : _c.isArray) {
202
+ var existing = resultObj[fieldName] || {
203
+ items: {},
204
+ };
205
+ var merged_1 = __assign(__assign({}, existing.items), selectionSet_1);
206
+ resultObj[fieldName] = { items: merged_1 };
207
+ return resultObj;
234
208
  }
209
+ var existingItems = resultObj[fieldName] || {};
210
+ var merged = __assign(__assign({}, existingItems), selectionSet_1);
211
+ resultObj[fieldName] = merged;
212
+ return resultObj;
235
213
  }
236
- }
237
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
238
- finally {
239
- try {
240
- if (selectionSet_1_1 && !selectionSet_1_1.done && (_a = selectionSet_1.return)) _a.call(selectionSet_1);
214
+ var exists = Boolean(modelFields[fieldName]);
215
+ if (!exists) {
216
+ throw Error("".concat(fieldName, " is not a field of model ").concat(modelName));
241
217
  }
242
- finally { if (e_2) throw e_2.error; }
243
- }
244
- return intermediateSelectionSet;
218
+ resultObj[fieldName] = FIELD_IR;
219
+ return resultObj;
220
+ }, {});
245
221
  }
222
+ var defaultSelectionSetIR = function (relatedModelDefinition) {
223
+ var defaultSelectionSet = defaultSelectionSetForModel(relatedModelDefinition);
224
+ var reduced = defaultSelectionSet.reduce(function (acc, curVal) {
225
+ acc[curVal] = FIELD_IR;
226
+ return acc;
227
+ }, {});
228
+ return reduced;
229
+ };
246
230
  /**
247
231
  * Stringifies selection set IR
248
232
  * * @example
@@ -326,9 +310,11 @@ export function generateGraphQLDocument(modelIntrospection, modelName, modelOper
326
310
  case 'LIST':
327
311
  graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = {
328
312
  filter: "Model".concat(name, "FilterInput"),
313
+ limit: 'Int',
314
+ nextToken: 'String',
329
315
  });
330
316
  graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'query');
331
- graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = "items { ".concat(selectionSetFields, " }"));
317
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = "items { ".concat(selectionSetFields, " } nextToken __typename"));
332
318
  case 'ONCREATE':
333
319
  case 'ONUPDATE':
334
320
  case 'ONDELETE':
@@ -337,6 +323,10 @@ export function generateGraphQLDocument(modelIntrospection, modelName, modelOper
337
323
  });
338
324
  graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'subscription');
339
325
  graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = selectionSetFields);
326
+ break;
327
+ case 'OBSERVE_QUERY':
328
+ default:
329
+ throw new Error('Internal error: Attempted to generate graphql document for observeQuery. Please report this error.');
340
330
  }
341
331
  var graphQLDocument = "".concat(graphQLOperationType).concat(graphQLArguments
342
332
  ? "(".concat(Object.entries(graphQLArguments).map(function (_a) {
@@ -384,6 +374,13 @@ export function buildGraphQLVariables(modelDefinition, operation, arg, modelIntr
384
374
  }
385
375
  break;
386
376
  case 'LIST':
377
+ if (arg === null || arg === void 0 ? void 0 : arg.filter) {
378
+ variables.filter = arg.filter;
379
+ }
380
+ if (arg === null || arg === void 0 ? void 0 : arg.nextToken) {
381
+ variables.nextToken = arg.nextToken;
382
+ }
383
+ break;
387
384
  case 'ONCREATE':
388
385
  case 'ONUPDATE':
389
386
  case 'ONDELETE':
@@ -391,6 +388,9 @@ export function buildGraphQLVariables(modelDefinition, operation, arg, modelIntr
391
388
  variables = { filter: arg.filter };
392
389
  }
393
390
  break;
391
+ case 'OBSERVE_QUERY':
392
+ throw new Error('Internal error: Attempted to build variables for observeQuery. Please report this error.');
393
+ break;
394
394
  default:
395
395
  var exhaustiveCheck = operation;
396
396
  throw new Error("Unhandled operation case: ".concat(exhaustiveCheck));
@@ -1,6 +1,7 @@
1
- import { __awaiter, __generator, __read, __values } from "tslib";
1
+ import { __assign, __awaiter, __generator, __read, __spreadArray, __values } from "tslib";
2
2
  import { initializeModel, generateGraphQLDocument, buildGraphQLVariables, graphQLOperationsInfo, flattenItems, } from './APIClient';
3
- import { map } from 'rxjs';
3
+ import { findIndexByFields, resolvePKFields } from '../utils';
4
+ import { Observable, map } from 'rxjs';
4
5
  export function generateModelsProperty(client, params) {
5
6
  var e_1, _a;
6
7
  var _this = this;
@@ -19,7 +20,7 @@ export function generateModelsProperty(client, params) {
19
20
  var operation = key;
20
21
  if (operation === 'LIST') {
21
22
  models[name_1][operationPrefix] = function (args) { return __awaiter(_this, void 0, void 0, function () {
22
- var query, variables, _a, data, nextToken, extensions, _b, key_1, flattenedResult, initialized, error_1;
23
+ var query, variables, _a, data, extensions, _b, key_1, flattenedResult, initialized, error_1;
23
24
  return __generator(this, function (_c) {
24
25
  switch (_c.label) {
25
26
  case 0:
@@ -33,7 +34,7 @@ export function generateModelsProperty(client, params) {
33
34
  variables: variables,
34
35
  })];
35
36
  case 2:
36
- _a = (_c.sent()), data = _a.data, nextToken = _a.nextToken, extensions = _a.extensions;
37
+ _a = (_c.sent()), data = _a.data, extensions = _a.extensions;
37
38
  // flatten response
38
39
  if (data !== undefined) {
39
40
  _b = __read(Object.keys(data), 1), key_1 = _b[0];
@@ -43,7 +44,7 @@ export function generateModelsProperty(client, params) {
43
44
  if (args === null || args === void 0 ? void 0 : args.selectionSet) {
44
45
  return [2 /*return*/, {
45
46
  data: flattenedResult,
46
- nextToken: nextToken,
47
+ nextToken: data[key_1].nextToken,
47
48
  extensions: extensions,
48
49
  }];
49
50
  }
@@ -51,14 +52,14 @@ export function generateModelsProperty(client, params) {
51
52
  initialized = initializeModel(client, name_1, flattenedResult, modelIntrospection);
52
53
  return [2 /*return*/, {
53
54
  data: initialized,
54
- nextToken: nextToken,
55
+ nextToken: data[key_1].nextToken,
55
56
  extensions: extensions,
56
57
  }];
57
58
  }
58
59
  }
59
60
  return [2 /*return*/, {
60
61
  data: data[key_1],
61
- nextToken: nextToken,
62
+ nextToken: data[key_1].nextToken,
62
63
  extensions: extensions,
63
64
  }];
64
65
  }
@@ -93,6 +94,163 @@ export function generateModelsProperty(client, params) {
93
94
  }));
94
95
  };
95
96
  }
97
+ else if (operation === 'OBSERVE_QUERY') {
98
+ models[name_1][operationPrefix] = function (arg, options) {
99
+ return new Observable(function (subscriber) {
100
+ // what we'll be sending to our subscribers
101
+ var items = [];
102
+ // To enqueue subscription messages while we collect our initial
103
+ // result set.
104
+ var messageQueue = [];
105
+ // operation to take when message(s) arrive.
106
+ // this operation will be swapped out once initial "sync" is complete
107
+ // to immediately ingest messsages.
108
+ var receiveMessages = function () {
109
+ var messages = [];
110
+ for (var _i = 0; _i < arguments.length; _i++) {
111
+ messages[_i] = arguments[_i];
112
+ }
113
+ return messageQueue.push.apply(messageQueue, __spreadArray([], __read(messages), false));
114
+ };
115
+ // start subscriptions
116
+ var onCreateSub = models[name_1]
117
+ .onCreate(arg, options)
118
+ .subscribe({
119
+ next: function (item) {
120
+ receiveMessages({ item: item, type: 'create' });
121
+ },
122
+ error: function (error) {
123
+ subscriber.error({ type: 'onCreate', error: error });
124
+ },
125
+ });
126
+ var onUpdateSub = models[name_1]
127
+ .onUpdate(arg, options)
128
+ .subscribe({
129
+ next: function (item) {
130
+ receiveMessages({ item: item, type: 'update' });
131
+ },
132
+ error: function (error) {
133
+ subscriber.error({ type: 'onUpdate', error: error });
134
+ },
135
+ });
136
+ var onDeleteSub = models[name_1]
137
+ .onDelete(arg, options)
138
+ .subscribe({
139
+ next: function (item) {
140
+ receiveMessages({ item: item, type: 'delete' });
141
+ },
142
+ error: function (error) {
143
+ subscriber.error({ type: 'onDelete', error: error });
144
+ },
145
+ });
146
+ // consumes a list of messages and sends a snapshot
147
+ function ingestMessages(messages) {
148
+ var e_2, _a;
149
+ try {
150
+ for (var messages_1 = __values(messages), messages_1_1 = messages_1.next(); !messages_1_1.done; messages_1_1 = messages_1.next()) {
151
+ var message = messages_1_1.value;
152
+ var idx = findIndexByFields(message.item, items, pkFields);
153
+ switch (message.type) {
154
+ case 'create':
155
+ if (idx < 0)
156
+ items.push(message.item);
157
+ break;
158
+ case 'update':
159
+ if (idx >= 0)
160
+ items[idx] = message.item;
161
+ break;
162
+ case 'delete':
163
+ if (idx >= 0)
164
+ items.splice(idx, 1);
165
+ break;
166
+ default:
167
+ console.error('Unrecognized message in observeQuery.', message);
168
+ }
169
+ }
170
+ }
171
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
172
+ finally {
173
+ try {
174
+ if (messages_1_1 && !messages_1_1.done && (_a = messages_1.return)) _a.call(messages_1);
175
+ }
176
+ finally { if (e_2) throw e_2.error; }
177
+ }
178
+ subscriber.next({
179
+ items: items,
180
+ isSynced: true,
181
+ });
182
+ }
183
+ var pkFields = resolvePKFields(model);
184
+ // initial results
185
+ (function () { return __awaiter(_this, void 0, void 0, function () {
186
+ var firstPage, nextToken, _a, page, errors, _nextToken, isSynced, errors_1, errors_1_1, error;
187
+ var e_3, _b;
188
+ return __generator(this, function (_c) {
189
+ switch (_c.label) {
190
+ case 0:
191
+ firstPage = true;
192
+ nextToken = null;
193
+ _c.label = 1;
194
+ case 1:
195
+ if (!(!subscriber.closed && (firstPage || nextToken))) return [3 /*break*/, 3];
196
+ firstPage = false;
197
+ return [4 /*yield*/, models[name_1].list(__assign(__assign({}, arg), { nextToken: nextToken }), options)];
198
+ case 2:
199
+ _a = _c.sent(), page = _a.data, errors = _a.errors, _nextToken = _a.nextToken;
200
+ nextToken = _nextToken;
201
+ items.push.apply(items, __spreadArray([], __read(page), false));
202
+ isSynced = messageQueue.length === 0 &&
203
+ (nextToken === null || nextToken === undefined);
204
+ subscriber.next({
205
+ items: items,
206
+ isSynced: isSynced,
207
+ });
208
+ if (Array.isArray(errors)) {
209
+ try {
210
+ for (errors_1 = (e_3 = void 0, __values(errors)), errors_1_1 = errors_1.next(); !errors_1_1.done; errors_1_1 = errors_1.next()) {
211
+ error = errors_1_1.value;
212
+ subscriber.error(error);
213
+ }
214
+ }
215
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
216
+ finally {
217
+ try {
218
+ if (errors_1_1 && !errors_1_1.done && (_b = errors_1.return)) _b.call(errors_1);
219
+ }
220
+ finally { if (e_3) throw e_3.error; }
221
+ }
222
+ }
223
+ return [3 /*break*/, 1];
224
+ case 3:
225
+ // play through the queue
226
+ if (messageQueue.length > 0) {
227
+ ingestMessages(messageQueue);
228
+ }
229
+ // switch the queue to write directly to the items collection
230
+ receiveMessages = function () {
231
+ var messages = [];
232
+ for (var _i = 0; _i < arguments.length; _i++) {
233
+ messages[_i] = arguments[_i];
234
+ }
235
+ ingestMessages(messages);
236
+ return items.length;
237
+ };
238
+ return [2 /*return*/];
239
+ }
240
+ });
241
+ }); })();
242
+ // when subscriber unsubscribes, tear down internal subs
243
+ return function () {
244
+ // 1. tear down internal subs
245
+ onCreateSub.unsubscribe();
246
+ onUpdateSub.unsubscribe();
247
+ onDeleteSub.unsubscribe();
248
+ // 2. there is no need to explicitly stop paging. instead, we
249
+ // just check `subscriber.closed` above before fetching each page.
250
+ };
251
+ });
252
+ };
253
+ }
96
254
  else {
97
255
  models[name_1][operationPrefix] = function (arg, options) { return __awaiter(_this, void 0, void 0, function () {
98
256
  var query, variables, _a, data, extensions, _b, key_2, flattenedResult, _c, initialized, error_2;