@aws-amplify/datastore 3.12.12 → 3.12.13-custom-pk.1

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 (105) hide show
  1. package/dist/aws-amplify-datastore.js +1854 -965
  2. package/dist/aws-amplify-datastore.js.map +1 -1
  3. package/dist/aws-amplify-datastore.min.js +7 -7
  4. package/dist/aws-amplify-datastore.min.js.map +1 -1
  5. package/lib/datastore/datastore.d.ts +13 -16
  6. package/lib/datastore/datastore.js +130 -63
  7. package/lib/datastore/datastore.js.map +1 -1
  8. package/lib/index.d.ts +3 -19
  9. package/lib/predicates/index.d.ts +3 -2
  10. package/lib/predicates/index.js +12 -2
  11. package/lib/predicates/index.js.map +1 -1
  12. package/lib/storage/adapter/AsyncStorageAdapter.d.ts +4 -3
  13. package/lib/storage/adapter/AsyncStorageAdapter.js +354 -203
  14. package/lib/storage/adapter/AsyncStorageAdapter.js.map +1 -1
  15. package/lib/storage/adapter/AsyncStorageDatabase.d.ts +14 -4
  16. package/lib/storage/adapter/AsyncStorageDatabase.js +65 -28
  17. package/lib/storage/adapter/AsyncStorageDatabase.js.map +1 -1
  18. package/lib/storage/adapter/IndexedDBAdapter.d.ts +5 -4
  19. package/lib/storage/adapter/IndexedDBAdapter.js +389 -267
  20. package/lib/storage/adapter/IndexedDBAdapter.js.map +1 -1
  21. package/lib/storage/adapter/index.d.ts +1 -1
  22. package/lib/storage/storage.d.ts +1 -1
  23. package/lib/storage/storage.js +92 -27
  24. package/lib/storage/storage.js.map +1 -1
  25. package/lib/sync/index.d.ts +21 -4
  26. package/lib/sync/index.js +13 -11
  27. package/lib/sync/index.js.map +1 -1
  28. package/lib/sync/merger.d.ts +3 -3
  29. package/lib/sync/merger.js +7 -6
  30. package/lib/sync/merger.js.map +1 -1
  31. package/lib/sync/outbox.d.ts +2 -2
  32. package/lib/sync/outbox.js +11 -9
  33. package/lib/sync/outbox.js.map +1 -1
  34. package/lib/sync/processors/mutation.js +60 -42
  35. package/lib/sync/processors/mutation.js.map +1 -1
  36. package/lib/sync/processors/subscription.js.map +1 -1
  37. package/lib/sync/processors/sync.js.map +1 -1
  38. package/lib/sync/utils.d.ts +3 -2
  39. package/lib/sync/utils.js +61 -8
  40. package/lib/sync/utils.js.map +1 -1
  41. package/lib/types.d.ts +64 -25
  42. package/lib/types.js +10 -1
  43. package/lib/types.js.map +1 -1
  44. package/lib/util.d.ts +56 -24
  45. package/lib/util.js +334 -170
  46. package/lib/util.js.map +1 -1
  47. package/lib-esm/datastore/datastore.d.ts +13 -16
  48. package/lib-esm/datastore/datastore.js +132 -65
  49. package/lib-esm/datastore/datastore.js.map +1 -1
  50. package/lib-esm/index.d.ts +3 -19
  51. package/lib-esm/predicates/index.d.ts +3 -2
  52. package/lib-esm/predicates/index.js +13 -3
  53. package/lib-esm/predicates/index.js.map +1 -1
  54. package/lib-esm/storage/adapter/AsyncStorageAdapter.d.ts +4 -3
  55. package/lib-esm/storage/adapter/AsyncStorageAdapter.js +355 -204
  56. package/lib-esm/storage/adapter/AsyncStorageAdapter.js.map +1 -1
  57. package/lib-esm/storage/adapter/AsyncStorageDatabase.d.ts +14 -4
  58. package/lib-esm/storage/adapter/AsyncStorageDatabase.js +66 -29
  59. package/lib-esm/storage/adapter/AsyncStorageDatabase.js.map +1 -1
  60. package/lib-esm/storage/adapter/IndexedDBAdapter.d.ts +5 -4
  61. package/lib-esm/storage/adapter/IndexedDBAdapter.js +390 -268
  62. package/lib-esm/storage/adapter/IndexedDBAdapter.js.map +1 -1
  63. package/lib-esm/storage/adapter/index.d.ts +1 -1
  64. package/lib-esm/storage/storage.d.ts +1 -1
  65. package/lib-esm/storage/storage.js +92 -27
  66. package/lib-esm/storage/storage.js.map +1 -1
  67. package/lib-esm/sync/index.d.ts +21 -4
  68. package/lib-esm/sync/index.js +15 -13
  69. package/lib-esm/sync/index.js.map +1 -1
  70. package/lib-esm/sync/merger.d.ts +3 -3
  71. package/lib-esm/sync/merger.js +7 -6
  72. package/lib-esm/sync/merger.js.map +1 -1
  73. package/lib-esm/sync/outbox.d.ts +2 -2
  74. package/lib-esm/sync/outbox.js +12 -10
  75. package/lib-esm/sync/outbox.js.map +1 -1
  76. package/lib-esm/sync/processors/mutation.js +61 -43
  77. package/lib-esm/sync/processors/mutation.js.map +1 -1
  78. package/lib-esm/sync/processors/subscription.js.map +1 -1
  79. package/lib-esm/sync/processors/sync.js.map +1 -1
  80. package/lib-esm/sync/utils.d.ts +3 -2
  81. package/lib-esm/sync/utils.js +62 -10
  82. package/lib-esm/sync/utils.js.map +1 -1
  83. package/lib-esm/types.d.ts +64 -25
  84. package/lib-esm/types.js +9 -2
  85. package/lib-esm/types.js.map +1 -1
  86. package/lib-esm/util.d.ts +56 -24
  87. package/lib-esm/util.js +334 -170
  88. package/lib-esm/util.js.map +1 -1
  89. package/package.json +7 -7
  90. package/src/datastore/datastore.ts +253 -113
  91. package/src/predicates/index.ts +32 -10
  92. package/src/storage/adapter/AsyncStorageAdapter.ts +309 -93
  93. package/src/storage/adapter/AsyncStorageDatabase.ts +74 -26
  94. package/src/storage/adapter/IndexedDBAdapter.ts +319 -136
  95. package/src/storage/adapter/index.ts +1 -1
  96. package/src/storage/storage.ts +68 -21
  97. package/src/sync/index.ts +41 -26
  98. package/src/sync/merger.ts +14 -4
  99. package/src/sync/outbox.ts +21 -8
  100. package/src/sync/processors/mutation.ts +49 -45
  101. package/src/sync/processors/subscription.ts +0 -1
  102. package/src/sync/processors/sync.ts +1 -3
  103. package/src/sync/utils.ts +69 -12
  104. package/src/types.ts +181 -29
  105. package/src/util.ts +415 -176
package/src/util.ts CHANGED
@@ -26,9 +26,41 @@ import {
26
26
  NonModelTypeConstructor,
27
27
  DeferredCallbackResolverOptions,
28
28
  LimitTimerRaceResolvedValues,
29
+ SchemaModel,
30
+ ModelAttribute,
31
+ IndexesType,
32
+ ModelAssociation,
29
33
  } from './types';
30
34
  import { WordArray } from 'amazon-cognito-identity-js';
31
35
 
36
+ export const ID = 'id';
37
+
38
+ /**
39
+ * Used by the Async Storage Adapter to concatenate key values
40
+ * for a record. For instance, if a model has the following keys:
41
+ * `customId: ID! @primaryKey(sortKeyFields: ["createdAt"])`,
42
+ * we concatenate the `customId` and `createdAt` as:
43
+ * `12-234-5#2022-09-28T00:00:00.000Z`
44
+ */
45
+ export const DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR = '#';
46
+
47
+ /**
48
+ * Used for generating spinal-cased index name from an array of
49
+ * key field names.
50
+ * E.g. for keys `[id, title]` => 'id-title'
51
+ */
52
+ export const IDENTIFIER_KEY_SEPARATOR = '-';
53
+
54
+ export const errorMessages = {
55
+ idEmptyString: 'An index field cannot contain an empty string value',
56
+ queryByPkWithCompositeKeyPresent:
57
+ 'Models with composite primary keys cannot be queried by a single key value. Use object literal syntax for composite keys instead: https://docs.amplify.aws/lib/datastore/advanced-workflows/q/platform/js/#querying-records-with-custom-primary-keys',
58
+ deleteByPkWithCompositeKeyPresent:
59
+ 'Models with composite primary keys cannot be deleted by a single key value, unless using a predicate. Use object literal syntax for composite keys instead: https://docs.amplify.aws/lib/datastore/advanced-workflows/q/platform/js/#querying-records-with-custom-primary-keys',
60
+ observeWithObjectLiteral:
61
+ 'Object literal syntax cannot be used with observe. Use a predicate instead: https://docs.amplify.aws/lib/datastore/data-access/q/platform/js/#predicates',
62
+ };
63
+
32
64
  export enum NAMESPACES {
33
65
  DATASTORE = 'datastore',
34
66
  USER = 'user',
@@ -162,154 +194,6 @@ export const isNonModelConstructor = (
162
194
  return nonModelClasses.has(obj);
163
195
  };
164
196
 
165
- /*
166
- When we have GSI(s) with composite sort keys defined on a model
167
- There are some very particular rules regarding which fields must be included in the update mutation input
168
- The field selection becomes more complex as the number of GSIs with composite sort keys grows
169
-
170
- To summarize: any time we update a field that is part of the composite sort key of a GSI, we must include:
171
- 1. all of the other fields in that composite sort key
172
- 2. all of the fields from any other composite sort key that intersect with the fields from 1.
173
-
174
- E.g.,
175
- Model @model
176
- @key(name: 'key1' fields: ['hk', 'a', 'b', 'c'])
177
- @key(name: 'key2' fields: ['hk', 'a', 'b', 'd'])
178
- @key(name: 'key3' fields: ['hk', 'x', 'y', 'z'])
179
-
180
- Model.a is updated => include ['a', 'b', 'c', 'd']
181
- Model.c is updated => include ['a', 'b', 'c', 'd']
182
- Model.d is updated => include ['a', 'b', 'c', 'd']
183
- Model.x is updated => include ['x', 'y', 'z']
184
-
185
- This function accepts a model's attributes and returns grouped sets of composite key fields
186
- Using our example Model above, the function will return:
187
- [
188
- Set('a', 'b', 'c', 'd'),
189
- Set('x', 'y', 'z'),
190
- ]
191
-
192
- This gives us the opportunity to correctly include the required fields for composite keys
193
- When crafting the mutation input in Storage.getUpdateMutationInput
194
-
195
- See 'processCompositeKeys' test in util.test.ts for more examples
196
- */
197
- export const processCompositeKeys = (
198
- attributes: ModelAttributes
199
- ): Set<string>[] => {
200
- const extractCompositeSortKey = ({
201
- properties: {
202
- // ignore the HK (fields[0]) we only need to include the composite sort key fields[1...n]
203
- fields: [, ...sortKeyFields],
204
- },
205
- }) => sortKeyFields;
206
-
207
- const compositeKeyFields = attributes
208
- .filter(isModelAttributeCompositeKey)
209
- .map(extractCompositeSortKey);
210
-
211
- /*
212
- if 2 sets of fields have any intersecting fields => combine them into 1 union set
213
- e.g., ['a', 'b', 'c'] and ['a', 'b', 'd'] => ['a', 'b', 'c', 'd']
214
- */
215
- const combineIntersecting = (fields): Set<string>[] =>
216
- fields.reduce((combined, sortKeyFields) => {
217
- const sortKeyFieldsSet = new Set(sortKeyFields);
218
-
219
- if (combined.length === 0) {
220
- combined.push(sortKeyFieldsSet);
221
- return combined;
222
- }
223
-
224
- // does the current set share values with another set we've already added to `combined`?
225
- const intersectingSetIdx = combined.findIndex(existingSet => {
226
- return [...existingSet].some(f => sortKeyFieldsSet.has(f));
227
- });
228
-
229
- if (intersectingSetIdx > -1) {
230
- const union = new Set([
231
- ...combined[intersectingSetIdx],
232
- ...sortKeyFieldsSet,
233
- ]);
234
- // combine the current set with the intersecting set we found above
235
- combined[intersectingSetIdx] = union;
236
- } else {
237
- // none of the sets in `combined` have intersecting values with the current set
238
- combined.push(sortKeyFieldsSet);
239
- }
240
-
241
- return combined;
242
- }, []);
243
-
244
- const initial = combineIntersecting(compositeKeyFields);
245
- // a single pass pay not be enough to correctly combine all the fields
246
- // call the function once more to get a final merged list of sets
247
- const combined = combineIntersecting(initial);
248
-
249
- return combined;
250
- };
251
-
252
- export const establishRelationAndKeys = (
253
- namespace: SchemaNamespace
254
- ): [RelationshipType, ModelKeys] => {
255
- const relationship: RelationshipType = {};
256
- const keys: ModelKeys = {};
257
-
258
- Object.keys(namespace.models).forEach((mKey: string) => {
259
- relationship[mKey] = { indexes: [], relationTypes: [] };
260
- keys[mKey] = {};
261
-
262
- const model = namespace.models[mKey];
263
- Object.keys(model.fields).forEach((attr: string) => {
264
- const fieldAttribute = model.fields[attr];
265
- if (
266
- typeof fieldAttribute.type === 'object' &&
267
- 'model' in fieldAttribute.type
268
- ) {
269
- const connectionType = fieldAttribute.association.connectionType;
270
- relationship[mKey].relationTypes.push({
271
- fieldName: fieldAttribute.name,
272
- modelName: fieldAttribute.type.model,
273
- relationType: connectionType,
274
- targetName: fieldAttribute.association['targetName'],
275
- associatedWith: fieldAttribute.association['associatedWith'],
276
- });
277
-
278
- if (connectionType === 'BELONGS_TO') {
279
- relationship[mKey].indexes.push(
280
- fieldAttribute.association['targetName']
281
- );
282
- }
283
- }
284
- });
285
-
286
- if (model.attributes) {
287
- keys[mKey].compositeKeys = processCompositeKeys(model.attributes);
288
-
289
- for (const attribute of model.attributes) {
290
- if (!isModelAttributeKey(attribute)) {
291
- continue;
292
- }
293
-
294
- if (isModelAttributePrimaryKey(attribute)) {
295
- keys[mKey].primaryKey = attribute.properties.fields;
296
- }
297
-
298
- const { fields } = attribute.properties;
299
- for (const field of fields) {
300
- // only add index if it hasn't already been added
301
- const exists = relationship[mKey].indexes.includes(field);
302
- if (!exists) {
303
- relationship[mKey].indexes.push(field);
304
- }
305
- }
306
- }
307
- }
308
- });
309
-
310
- return [relationship, keys];
311
- };
312
-
313
197
  const topologicallySortedModels = new WeakMap<SchemaNamespace, string[]>();
314
198
 
315
199
  export const traverseModel = <T extends PersistentModel>(
@@ -323,12 +207,14 @@ export const traverseModel = <T extends PersistentModel>(
323
207
  ) => PersistentModelConstructor<any>
324
208
  ) => {
325
209
  const relationships = namespace.relationships;
210
+
326
211
  const modelConstructor = getModelConstructorByModelName(
327
212
  namespace.name,
328
213
  srcModelName
329
214
  );
330
215
 
331
216
  const relation = relationships[srcModelName];
217
+
332
218
  const result: {
333
219
  modelName: string;
334
220
  item: T;
@@ -362,15 +248,36 @@ export const traverseModel = <T extends PersistentModel>(
362
248
  instance: modelInstance,
363
249
  });
364
250
 
365
- // targetName will be defined for Has One if feature flag
251
+ const targetNames: string[] | undefined =
252
+ extractTargetNamesFromSrc(rItem);
253
+
254
+ // `targetName` will be defined for Has One if feature flag
366
255
  // https://docs.amplify.aws/cli/reference/feature-flags/#useAppsyncModelgenPlugin
367
256
  // is true (default as of 5/7/21)
368
257
  // Making this conditional for backward-compatibility
369
- if (rItem.targetName) {
370
- (<any>draftInstance)[rItem.targetName] = (<PersistentModel>(
371
- draftInstance[rItem.fieldName]
372
- )).id;
373
- delete draftInstance[rItem.fieldName];
258
+ if (targetNames) {
259
+ targetNames.forEach((targetName, idx) => {
260
+ // Get the connected record
261
+ const relatedRecordInProxy = <PersistentModel>(
262
+ draftInstance[rItem.fieldName]
263
+ );
264
+
265
+ // Previously, we used the hardcoded 'id' as they key,
266
+ // now we need the value of the key to get the PK (and SK)
267
+ // values from the related record
268
+
269
+ const { primaryKey } = namespace.keys[modelConstructor.name];
270
+ const keyField = primaryKey && primaryKey[idx];
271
+
272
+ // Get the value
273
+ const relatedRecordInProxyPkValue =
274
+ relatedRecordInProxy[keyField];
275
+
276
+ // Set the targetName value
277
+ (<any>draftInstance)[targetName] = relatedRecordInProxyPkValue;
278
+ });
279
+ // Delete the instance from the proxy
280
+ delete (<any>draftInstance)[rItem.fieldName];
374
281
  } else {
375
282
  (<any>draftInstance)[rItem.fieldName] = (<PersistentModel>(
376
283
  draftInstance[rItem.fieldName]
@@ -405,10 +312,33 @@ export const traverseModel = <T extends PersistentModel>(
405
312
  }
406
313
 
407
314
  if (draftInstance[rItem.fieldName]) {
408
- (<any>draftInstance)[rItem.targetName] = (<PersistentModel>(
409
- draftInstance[rItem.fieldName]
410
- )).id;
411
- delete draftInstance[rItem.fieldName];
315
+ const targetNames: string[] | undefined =
316
+ extractTargetNamesFromSrc(rItem);
317
+
318
+ if (targetNames) {
319
+ targetNames.forEach((targetName, idx) => {
320
+ // Get the connected record
321
+ const relatedRecordInProxy = <PersistentModel>(
322
+ draftInstance[rItem.fieldName]
323
+ );
324
+ // Previously, we used the hardcoded `id` for the key.
325
+ // Now, we need the value of the key to get the PK (and SK)
326
+ // values from the related record
327
+ const { primaryKey } = namespace.keys[modelConstructor.name];
328
+
329
+ // fall back to ID if
330
+ const keyField = primaryKey && primaryKey[idx];
331
+
332
+ // Get the value
333
+ const relatedRecordInProxyPkValue =
334
+ relatedRecordInProxy[keyField];
335
+
336
+ // Set the targetName value
337
+ (<any>draftInstance)[targetName] = relatedRecordInProxyPkValue;
338
+ });
339
+ // Delete the instance from the proxy
340
+ delete (<any>draftInstance)[rItem.fieldName];
341
+ }
412
342
  }
413
343
 
414
344
  break;
@@ -446,24 +376,6 @@ export const traverseModel = <T extends PersistentModel>(
446
376
  return result;
447
377
  };
448
378
 
449
- export const getIndex = (rel: RelationType[], src: string): string => {
450
- let index = '';
451
- rel.some((relItem: RelationType) => {
452
- if (relItem.modelName === src) {
453
- index = relItem.targetName;
454
- }
455
- });
456
- return index;
457
- };
458
-
459
- export const getIndexFromAssociation = (
460
- indexes: string[],
461
- src: string
462
- ): string => {
463
- const index = indexes.find(idx => idx === src);
464
- return index;
465
- };
466
-
467
379
  let privateModeCheckResult;
468
380
 
469
381
  export const isPrivateMode = () => {
@@ -811,3 +723,330 @@ export function mergePatches<T>(
811
723
  );
812
724
  return patches;
813
725
  }
726
+
727
+ export const getStorename = (namespace: string, modelName: string) => {
728
+ const storeName = `${namespace}_${modelName}`;
729
+
730
+ return storeName;
731
+ };
732
+
733
+ //#region Key Utils
734
+
735
+ /*
736
+ When we have GSI(s) with composite sort keys defined on a model
737
+ There are some very particular rules regarding which fields must be included in the update mutation input
738
+ The field selection becomes more complex as the number of GSIs with composite sort keys grows
739
+
740
+ To summarize: any time we update a field that is part of the composite sort key of a GSI, we must include:
741
+ 1. all of the other fields in that composite sort key
742
+ 2. all of the fields from any other composite sort key that intersect with the fields from 1.
743
+
744
+ E.g.,
745
+ Model @model
746
+ @key(name: 'key1' fields: ['hk', 'a', 'b', 'c'])
747
+ @key(name: 'key2' fields: ['hk', 'a', 'b', 'd'])
748
+ @key(name: 'key3' fields: ['hk', 'x', 'y', 'z'])
749
+
750
+ Model.a is updated => include ['a', 'b', 'c', 'd']
751
+ Model.c is updated => include ['a', 'b', 'c', 'd']
752
+ Model.d is updated => include ['a', 'b', 'c', 'd']
753
+ Model.x is updated => include ['x', 'y', 'z']
754
+
755
+ This function accepts a model's attributes and returns grouped sets of composite key fields
756
+ Using our example Model above, the function will return:
757
+ [
758
+ Set('a', 'b', 'c', 'd'),
759
+ Set('x', 'y', 'z'),
760
+ ]
761
+
762
+ This gives us the opportunity to correctly include the required fields for composite keys
763
+ When crafting the mutation input in Storage.getUpdateMutationInput
764
+
765
+ See 'processCompositeKeys' test in util.test.ts for more examples
766
+ */
767
+ export const processCompositeKeys = (
768
+ attributes: ModelAttributes
769
+ ): Set<string>[] => {
770
+ const extractCompositeSortKey = ({
771
+ properties: {
772
+ // ignore the HK (fields[0]) we only need to include the composite sort key fields[1...n]
773
+ fields: [, ...sortKeyFields],
774
+ },
775
+ }) => sortKeyFields;
776
+
777
+ const compositeKeyFields = attributes
778
+ .filter(isModelAttributeCompositeKey)
779
+ .map(extractCompositeSortKey);
780
+
781
+ /*
782
+ if 2 sets of fields have any intersecting fields => combine them into 1 union set
783
+ e.g., ['a', 'b', 'c'] and ['a', 'b', 'd'] => ['a', 'b', 'c', 'd']
784
+ */
785
+ const combineIntersecting = (fields): Set<string>[] =>
786
+ fields.reduce((combined, sortKeyFields) => {
787
+ const sortKeyFieldsSet = new Set(sortKeyFields);
788
+
789
+ if (combined.length === 0) {
790
+ combined.push(sortKeyFieldsSet);
791
+ return combined;
792
+ }
793
+
794
+ // does the current set share values with another set we've already added to `combined`?
795
+ const intersectingSetIdx = combined.findIndex(existingSet => {
796
+ return [...existingSet].some(f => sortKeyFieldsSet.has(f));
797
+ });
798
+
799
+ if (intersectingSetIdx > -1) {
800
+ const union = new Set([
801
+ ...combined[intersectingSetIdx],
802
+ ...sortKeyFieldsSet,
803
+ ]);
804
+ // combine the current set with the intersecting set we found above
805
+ combined[intersectingSetIdx] = union;
806
+ } else {
807
+ // none of the sets in `combined` have intersecting values with the current set
808
+ combined.push(sortKeyFieldsSet);
809
+ }
810
+
811
+ return combined;
812
+ }, []);
813
+
814
+ const initial = combineIntersecting(compositeKeyFields);
815
+ // a single pass pay not be enough to correctly combine all the fields
816
+ // call the function once more to get a final merged list of sets
817
+ const combined = combineIntersecting(initial);
818
+
819
+ return combined;
820
+ };
821
+
822
+ export const extractKeyIfExists = (
823
+ modelDefinition: SchemaModel
824
+ ): ModelAttribute | undefined => {
825
+ const keyAttribute = modelDefinition?.attributes?.find(isModelAttributeKey);
826
+
827
+ return keyAttribute;
828
+ };
829
+
830
+ export const extractPrimaryKeyFieldNames = (
831
+ modelDefinition: SchemaModel
832
+ ): string[] => {
833
+ const keyAttribute = extractKeyIfExists(modelDefinition);
834
+ if (keyAttribute && isModelAttributePrimaryKey(keyAttribute)) {
835
+ return keyAttribute.properties.fields;
836
+ }
837
+
838
+ return [ID];
839
+ };
840
+
841
+ export const extractPrimaryKeyValues = <T extends PersistentModel>(
842
+ model: T,
843
+ keyFields: string[]
844
+ ): string[] => {
845
+ return keyFields.map(key => model[key]);
846
+ };
847
+
848
+ export const extractPrimaryKeysAndValues = <T extends PersistentModel>(
849
+ model: T,
850
+ keyFields: string[]
851
+ ): any => {
852
+ const primaryKeysAndValues = {};
853
+ keyFields.forEach(key => (primaryKeysAndValues[key] = model[key]));
854
+ return primaryKeysAndValues;
855
+ };
856
+
857
+ // IdentifierFields<ManagedIdentifier>
858
+ // Default behavior without explicit @primaryKey defined
859
+ export const isIdManaged = (modelDefinition: SchemaModel): boolean => {
860
+ const keyAttribute = extractKeyIfExists(modelDefinition);
861
+
862
+ if (keyAttribute && isModelAttributePrimaryKey(keyAttribute)) {
863
+ return false;
864
+ }
865
+
866
+ return true;
867
+ };
868
+
869
+ // IdentifierFields<OptionallyManagedIdentifier>
870
+ // @primaryKey with explicit `id` in the PK. Single key or composite
871
+ export const isIdOptionallyManaged = (
872
+ modelDefinition: SchemaModel
873
+ ): boolean => {
874
+ const keyAttribute = extractKeyIfExists(modelDefinition);
875
+
876
+ if (keyAttribute && isModelAttributePrimaryKey(keyAttribute)) {
877
+ return keyAttribute.properties.fields[0] === ID;
878
+ }
879
+
880
+ return false;
881
+ };
882
+
883
+ export const establishRelationAndKeys = (
884
+ namespace: SchemaNamespace
885
+ ): [RelationshipType, ModelKeys] => {
886
+ const relationship: RelationshipType = {};
887
+ const keys: ModelKeys = {};
888
+
889
+ Object.keys(namespace.models).forEach((mKey: string) => {
890
+ relationship[mKey] = { indexes: [], relationTypes: [] };
891
+ keys[mKey] = {};
892
+
893
+ const model = namespace.models[mKey];
894
+ Object.keys(model.fields).forEach((attr: string) => {
895
+ const fieldAttribute = model.fields[attr];
896
+ if (
897
+ typeof fieldAttribute.type === 'object' &&
898
+ 'model' in fieldAttribute.type
899
+ ) {
900
+ const connectionType = fieldAttribute.association.connectionType;
901
+ relationship[mKey].relationTypes.push({
902
+ fieldName: fieldAttribute.name,
903
+ modelName: fieldAttribute.type.model,
904
+ relationType: connectionType,
905
+ targetName: fieldAttribute.association['targetName'],
906
+ targetNames: fieldAttribute.association['targetNames'],
907
+ associatedWith: fieldAttribute.association['associatedWith'],
908
+ });
909
+
910
+ if (connectionType === 'BELONGS_TO') {
911
+ const targetNames = extractTargetNamesFromSrc(
912
+ fieldAttribute.association
913
+ );
914
+
915
+ if (targetNames) {
916
+ const idxName = indexNameFromKeys(targetNames);
917
+ relationship[mKey].indexes.push([idxName, targetNames]);
918
+ }
919
+ }
920
+ }
921
+ });
922
+
923
+ if (model.attributes) {
924
+ keys[mKey].compositeKeys = processCompositeKeys(model.attributes);
925
+
926
+ for (const attribute of model.attributes) {
927
+ if (!isModelAttributeKey(attribute)) {
928
+ continue;
929
+ }
930
+
931
+ const { fields } = attribute.properties;
932
+
933
+ if (isModelAttributePrimaryKey(attribute)) {
934
+ keys[mKey].primaryKey = fields;
935
+ continue;
936
+ }
937
+
938
+ // create indexes for all other keys
939
+ const idxName = indexNameFromKeys(fields);
940
+ const idxExists = relationship[mKey].indexes.find(
941
+ ([index]) => index === idxName
942
+ );
943
+
944
+ if (!idxExists) {
945
+ relationship[mKey].indexes.push([idxName, fields]);
946
+ }
947
+ }
948
+ }
949
+
950
+ // set 'id' as the PK for models without a custom PK explicitly defined
951
+ if (!keys[mKey].primaryKey) {
952
+ keys[mKey].primaryKey = [ID];
953
+ }
954
+
955
+ // create primary index
956
+ relationship[mKey].indexes.push([
957
+ 'byPk',
958
+ keys[mKey].primaryKey as string[],
959
+ { unique: true },
960
+ ]);
961
+ });
962
+
963
+ return [relationship, keys];
964
+ };
965
+
966
+ export const getIndex = (
967
+ rel: RelationType[],
968
+ src: string
969
+ ): string | undefined => {
970
+ let indexName;
971
+ rel.some((relItem: RelationType) => {
972
+ if (relItem.modelName === src) {
973
+ const targetNames = extractTargetNamesFromSrc(relItem);
974
+ indexName = targetNames && indexNameFromKeys(targetNames);
975
+ return true;
976
+ }
977
+ });
978
+ return indexName;
979
+ };
980
+
981
+ export const getIndexFromAssociation = (
982
+ indexes: IndexesType,
983
+ src: string | string[]
984
+ ): string | undefined => {
985
+ let indexName: string;
986
+
987
+ if (Array.isArray(src)) {
988
+ indexName = indexNameFromKeys(src);
989
+ } else {
990
+ indexName = src;
991
+ }
992
+
993
+ const associationIndex = indexes.find(([idxName]) => idxName === indexName);
994
+ return associationIndex && associationIndex[0];
995
+ };
996
+
997
+ /**
998
+ * Backwards-compatability for schema generated prior to custom primary key support:
999
+ the single field `targetName` has been replaced with an array of `targetNames`.
1000
+ `targetName` and `targetNames` are exclusive (will never exist on the same schema)
1001
+ * @param src {RelationType | ModelAssociation | undefined}
1002
+ * @returns array of targetNames, or `undefined`
1003
+ */
1004
+ export const extractTargetNamesFromSrc = (
1005
+ src: RelationType | ModelAssociation | undefined
1006
+ ): string[] | undefined => {
1007
+ const targetName = src?.targetName;
1008
+ const targetNames = src?.targetNames;
1009
+
1010
+ if (Array.isArray(targetNames)) {
1011
+ return targetNames;
1012
+ } else if (typeof targetName === 'string') {
1013
+ return [targetName];
1014
+ } else {
1015
+ return undefined;
1016
+ }
1017
+ };
1018
+
1019
+ // Generates spinal-cased index name from an array of key field names
1020
+ // E.g. for keys `[id, title]` => 'id-title'
1021
+ export const indexNameFromKeys = (keys: string[]): string => {
1022
+ return keys.reduce((prev: string, cur: string, idx: number) => {
1023
+ if (idx === 0) {
1024
+ return cur;
1025
+ }
1026
+ return `${prev}${IDENTIFIER_KEY_SEPARATOR}${cur}`;
1027
+ }, '');
1028
+ };
1029
+
1030
+ export const keysEqual = (keysA, keysB): boolean => {
1031
+ if (keysA.length !== keysB.length) {
1032
+ return false;
1033
+ }
1034
+
1035
+ return keysA.every((key, idx) => key === keysB[idx]);
1036
+ };
1037
+
1038
+ // Returns primary keys for a model
1039
+ export const getIndexKeys = (
1040
+ namespace: SchemaNamespace,
1041
+ modelName: string
1042
+ ): string[] => {
1043
+ const keyPath = namespace?.keys[modelName]?.primaryKey;
1044
+
1045
+ if (keyPath) {
1046
+ return keyPath;
1047
+ }
1048
+
1049
+ return [ID];
1050
+ };
1051
+
1052
+ //#endregion