@aws-amplify/api-graphql 4.0.1-api-v6-models.9493d4d.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,6 +140,7 @@ 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
146
  var SELECTION_SET_WILDCARD = '*';
@@ -309,9 +310,11 @@ export function generateGraphQLDocument(modelIntrospection, modelName, modelOper
309
310
  case 'LIST':
310
311
  graphQLArguments !== null && graphQLArguments !== void 0 ? graphQLArguments : (graphQLArguments = {
311
312
  filter: "Model".concat(name, "FilterInput"),
313
+ limit: 'Int',
314
+ nextToken: 'String',
312
315
  });
313
316
  graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'query');
314
- graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = "items { ".concat(selectionSetFields, " }"));
317
+ graphQLSelectionSet !== null && graphQLSelectionSet !== void 0 ? graphQLSelectionSet : (graphQLSelectionSet = "items { ".concat(selectionSetFields, " } nextToken __typename"));
315
318
  case 'ONCREATE':
316
319
  case 'ONUPDATE':
317
320
  case 'ONDELETE':
@@ -320,6 +323,10 @@ export function generateGraphQLDocument(modelIntrospection, modelName, modelOper
320
323
  });
321
324
  graphQLOperationType !== null && graphQLOperationType !== void 0 ? graphQLOperationType : (graphQLOperationType = 'subscription');
322
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.');
323
330
  }
324
331
  var graphQLDocument = "".concat(graphQLOperationType).concat(graphQLArguments
325
332
  ? "(".concat(Object.entries(graphQLArguments).map(function (_a) {
@@ -367,6 +374,13 @@ export function buildGraphQLVariables(modelDefinition, operation, arg, modelIntr
367
374
  }
368
375
  break;
369
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;
370
384
  case 'ONCREATE':
371
385
  case 'ONUPDATE':
372
386
  case 'ONDELETE':
@@ -374,6 +388,9 @@ export function buildGraphQLVariables(modelDefinition, operation, arg, modelIntr
374
388
  variables = { filter: arg.filter };
375
389
  }
376
390
  break;
391
+ case 'OBSERVE_QUERY':
392
+ throw new Error('Internal error: Attempted to build variables for observeQuery. Please report this error.');
393
+ break;
377
394
  default:
378
395
  var exhaustiveCheck = operation;
379
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;