@snteam/amplify-angular-core 1.0.40 → 1.0.41

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.
@@ -2296,11 +2296,29 @@ class AmplifyModelService {
2296
2296
  selectionSetGenerator;
2297
2297
  errorHandler;
2298
2298
  client;
2299
+ relationshipConfig = null;
2299
2300
  constructor(selectionSetGenerator, errorHandler) {
2300
2301
  this.selectionSetGenerator = selectionSetGenerator;
2301
2302
  this.errorHandler = errorHandler;
2302
2303
  // Client will be initialized when Amplify is configured by the consuming application
2303
2304
  }
2305
+ /**
2306
+ * Configure the service with relationship selection sets
2307
+ * This should be called by the consuming application to define how relationships should be queried
2308
+ */
2309
+ configure(config) {
2310
+ if (config.relationshipSelectionSets) {
2311
+ this.relationshipConfig = config.relationshipSelectionSets;
2312
+ console.log('AmplifyModelService: Configured with relationship selection sets:', this.relationshipConfig);
2313
+ }
2314
+ }
2315
+ /**
2316
+ * Set relationship selection set configuration directly
2317
+ */
2318
+ setRelationshipConfig(config) {
2319
+ this.relationshipConfig = config;
2320
+ console.log('AmplifyModelService: Updated relationship selection sets configuration:', this.relationshipConfig);
2321
+ }
2304
2322
  /**
2305
2323
  * Initialize the service with the Amplify client
2306
2324
  * This should be called by the consuming application after Amplify.configure()
@@ -2486,9 +2504,8 @@ class AmplifyModelService {
2486
2504
  }
2487
2505
  }
2488
2506
  /**
2489
- * Generate dynamic selection set for relationship queries
2490
- * Replaces hardcoded selection set logic with dynamic generation
2491
- * Enhanced with comprehensive error handling and logging
2507
+ * Get selection set for relationship queries using configuration
2508
+ * This replaces the complex dynamic generation with simple configuration lookup
2492
2509
  * @param config Relationship configuration object
2493
2510
  * @param baseId Base record ID (for compatibility, not used in generation)
2494
2511
  * @returns Array of GraphQL field selectors
@@ -2496,65 +2513,89 @@ class AmplifyModelService {
2496
2513
  getAmplifySelectionSet(config, baseId) {
2497
2514
  try {
2498
2515
  if (!config) {
2499
- const error = this.errorHandler.logSelectionSetError(SelectionSetErrorType.INVALID_CONFIGURATION, 'Configuration is null or undefined', config, undefined, {
2500
- method: 'getAmplifySelectionSet',
2501
- baseId,
2502
- clientAvailable: !!this.client
2503
- });
2504
- // Return minimal fallback
2516
+ console.warn('AmplifyModelService: Configuration is null or undefined, using minimal fallback');
2505
2517
  return ['id'];
2506
2518
  }
2507
- console.log('AmplifyModelService: Generating dynamic selection set for config:', {
2519
+ console.log('AmplifyModelService: Getting selection set for relationship:', {
2508
2520
  relationshipModel: config.relationshipModelName,
2509
2521
  fieldName: config.fieldName,
2510
2522
  baseModelName: config.baseModelName,
2511
2523
  associatedWith: config.associatedWith,
2512
2524
  baseId
2513
2525
  });
2514
- // Use the SelectionSetGenerator to create dynamic selection sets
2515
- const selectionSet = this.selectionSetGenerator.generateSelectionSet(config);
2516
- if (!selectionSet || selectionSet.length === 0) {
2517
- const error = this.errorHandler.logSelectionSetError(SelectionSetErrorType.GRAPHQL_ERROR, 'Selection set generator returned empty or null result', config, selectionSet, {
2518
- method: 'getAmplifySelectionSet',
2519
- baseId,
2520
- generatorAvailable: !!this.selectionSetGenerator
2521
- });
2522
- // Return minimal fallback
2523
- console.warn('AmplifyModelService: Using minimal fallback selection set due to generator failure');
2524
- return ['id'];
2525
- }
2526
- console.log('AmplifyModelService: Generated selection set:', {
2527
- config: config.fieldName,
2528
- selectionSetLength: selectionSet.length,
2529
- selectionSet,
2530
- detailedConfig: {
2531
- relationshipModelName: config.relationshipModelName,
2532
- baseModelName: config.baseModelName,
2533
- fieldName: config.fieldName,
2534
- associatedWith: config.associatedWith
2526
+ // Try to get selection set from configuration first
2527
+ const configuredSelectionSet = this.getConfiguredSelectionSet(config);
2528
+ if (configuredSelectionSet && configuredSelectionSet.length > 0) {
2529
+ console.log('AmplifyModelService: Using configured selection set:', configuredSelectionSet);
2530
+ return configuredSelectionSet;
2531
+ }
2532
+ // Fall back to default selection set if configured
2533
+ if (this.relationshipConfig?.defaultSelectionSet && this.relationshipConfig.defaultSelectionSet.length > 0) {
2534
+ console.log('AmplifyModelService: Using default configured selection set:', this.relationshipConfig.defaultSelectionSet);
2535
+ return this.relationshipConfig.defaultSelectionSet;
2536
+ }
2537
+ // Fall back to dynamic generation if enabled and no configuration found
2538
+ if (this.relationshipConfig?.enableFallback !== false) {
2539
+ console.log('AmplifyModelService: No configuration found, falling back to dynamic generation');
2540
+ const dynamicSelectionSet = this.selectionSetGenerator.generateSelectionSet(config);
2541
+ if (dynamicSelectionSet && dynamicSelectionSet.length > 0) {
2542
+ console.log('AmplifyModelService: Using dynamic selection set:', dynamicSelectionSet);
2543
+ return dynamicSelectionSet;
2535
2544
  }
2536
- });
2537
- return selectionSet;
2545
+ }
2546
+ // Final fallback - use a simple, predictable selection set
2547
+ const fallbackSelectionSet = this.generateSimpleFallbackSelectionSet(config);
2548
+ console.log('AmplifyModelService: Using simple fallback selection set:', fallbackSelectionSet);
2549
+ return fallbackSelectionSet;
2538
2550
  }
2539
2551
  catch (error) {
2540
- const selectionSetError = this.errorHandler.logSelectionSetError(SelectionSetErrorType.GRAPHQL_ERROR, `Unexpected error generating selection set: ${error instanceof Error ? error.message : String(error)}`, config, undefined, {
2541
- method: 'getAmplifySelectionSet',
2542
- baseId,
2543
- originalError: {
2544
- message: error instanceof Error ? error.message : String(error),
2545
- stack: error instanceof Error ? error.stack : undefined,
2546
- type: typeof error
2547
- },
2548
- context: {
2549
- clientAvailable: !!this.client,
2550
- selectionSetGeneratorAvailable: !!this.selectionSetGenerator
2551
- }
2552
- });
2553
- console.error('AmplifyModelService: Error generating selection set, using fallback:', error);
2554
- // Use fallback selection set generation with retry logic
2555
- return this.selectionSetGenerator.generateFallbackSelectionSetWithRetry(config?.fieldName || '', [error instanceof Error ? error.message : String(error)]);
2552
+ console.error('AmplifyModelService: Error getting selection set, using minimal fallback:', error);
2553
+ return ['id'];
2556
2554
  }
2557
2555
  }
2556
+ /**
2557
+ * Get configured selection set for a specific relationship
2558
+ */
2559
+ getConfiguredSelectionSet(config) {
2560
+ if (!this.relationshipConfig?.relationships) {
2561
+ return null;
2562
+ }
2563
+ // Look for exact match first
2564
+ const exactMatch = this.relationshipConfig.relationships.find(rel => rel.relationshipModel === config.relationshipModelName &&
2565
+ rel.fieldName === config.fieldName);
2566
+ if (exactMatch) {
2567
+ console.log('AmplifyModelService: Found exact configuration match:', exactMatch);
2568
+ return exactMatch.selectionSet;
2569
+ }
2570
+ // Look for relationship model match
2571
+ const modelMatch = this.relationshipConfig.relationships.find(rel => rel.relationshipModel === config.relationshipModelName);
2572
+ if (modelMatch) {
2573
+ console.log('AmplifyModelService: Found relationship model match:', modelMatch);
2574
+ return modelMatch.selectionSet;
2575
+ }
2576
+ // Look for field name match
2577
+ const fieldMatch = this.relationshipConfig.relationships.find(rel => rel.fieldName === config.fieldName);
2578
+ if (fieldMatch) {
2579
+ console.log('AmplifyModelService: Found field name match:', fieldMatch);
2580
+ return fieldMatch.selectionSet;
2581
+ }
2582
+ return null;
2583
+ }
2584
+ /**
2585
+ * Generate a simple, predictable fallback selection set
2586
+ */
2587
+ generateSimpleFallbackSelectionSet(config) {
2588
+ const selectionSet = ['id'];
2589
+ if (config.fieldName) {
2590
+ // Add the relationship field itself
2591
+ selectionSet.push(config.fieldName);
2592
+ // Add common nested fields
2593
+ selectionSet.push(`${config.fieldName}.id`);
2594
+ selectionSet.push(`${config.fieldName}.name`);
2595
+ selectionSet.push(`${config.fieldName}.title`);
2596
+ }
2597
+ return selectionSet;
2598
+ }
2558
2599
  setRelatedSub(config, baseId) {
2559
2600
  if (!this.client) {
2560
2601
  console.error('AmplifyModelService: Client not initialized. Call initializeClient() first.');
@@ -2757,178 +2798,44 @@ class AmplifyModelService {
2757
2798
  }
2758
2799
  /**
2759
2800
  * Validate that relationship field data is populated in query results
2760
- * Enhanced with comprehensive error logging and very flexible validation
2801
+ * Simplified validation that's more predictable and easier to debug
2761
2802
  */
2762
2803
  validateRelationshipFieldPopulation(result, config) {
2763
2804
  try {
2764
2805
  if (!result || !result.data) {
2765
- this.errorHandler.logSelectionSetError(SelectionSetErrorType.GRAPHQL_ERROR, 'Query result is missing or has no data property', config, undefined, {
2766
- method: 'validateRelationshipFieldPopulation',
2767
- hasResult: !!result,
2768
- hasData: !!(result?.data),
2769
- resultType: typeof result,
2770
- resultKeys: result ? Object.keys(result) : []
2771
- });
2806
+ console.warn('AmplifyModelService: Query result is missing or has no data property');
2772
2807
  return false;
2773
2808
  }
2774
- // Check if any records have the relationship field populated
2775
2809
  const records = Array.isArray(result.data) ? result.data : [result.data];
2776
- let populatedCount = 0;
2777
- let partiallyPopulatedCount = 0;
2778
- let recordsWithAnyRelationshipData = 0;
2810
+ if (records.length === 0) {
2811
+ console.warn('AmplifyModelService: No records returned from query');
2812
+ return false;
2813
+ }
2779
2814
  console.log(`AmplifyModelService: Validating relationship field '${config.fieldName}' in ${records.length} records`);
2815
+ // Simple validation: if we have records, consider it successful
2816
+ // The actual relationship data validation will happen at the UI level
2817
+ let hasAnyData = false;
2780
2818
  for (let i = 0; i < records.length; i++) {
2781
2819
  const record = records[i];
2782
- if (!record)
2783
- continue;
2784
- console.log(`AmplifyModelService: Checking record ${i}:`, {
2785
- recordKeys: Object.keys(record),
2786
- fieldName: config.fieldName,
2787
- fieldValue: record[config.fieldName],
2788
- fieldType: typeof record[config.fieldName]
2789
- });
2790
- const relationshipData = record[config.fieldName];
2791
- // Strategy 1: Check for fully populated relationship (object with data)
2792
- if (relationshipData !== undefined && relationshipData !== null) {
2793
- console.log(`AmplifyModelService: Record ${i} has relationship data:`, relationshipData);
2794
- // If it's an object with properties, consider it populated
2795
- if (typeof relationshipData === 'object' && Object.keys(relationshipData).length > 0) {
2796
- populatedCount++;
2797
- recordsWithAnyRelationshipData++;
2798
- }
2799
- // If it's a non-null primitive value, also consider it populated
2800
- else if (typeof relationshipData !== 'object') {
2801
- populatedCount++;
2802
- recordsWithAnyRelationshipData++;
2803
- }
2804
- // If it's an empty object or array, consider it partially populated
2805
- else {
2806
- partiallyPopulatedCount++;
2807
- recordsWithAnyRelationshipData++;
2808
- }
2809
- }
2810
- // Strategy 2: Check if the record has any nested relationship data
2811
- // This handles cases where the selection set includes nested fields like "table.id", "table.name"
2812
- const hasNestedRelationshipData = this.hasNestedRelationshipData(record, config.fieldName);
2813
- if (hasNestedRelationshipData) {
2814
- console.log(`AmplifyModelService: Record ${i} has nested relationship data for field '${config.fieldName}'`);
2815
- populatedCount++;
2816
- recordsWithAnyRelationshipData++;
2817
- }
2818
- // Strategy 3: Check for any field that contains the relationship name
2819
- // This is a very permissive check for cases where the field structure is different
2820
- const hasAnyRelatedField = this.hasAnyRelatedField(record, config.fieldName);
2821
- if (hasAnyRelatedField) {
2822
- console.log(`AmplifyModelService: Record ${i} has some related field data for '${config.fieldName}'`);
2823
- recordsWithAnyRelationshipData++;
2820
+ if (record && typeof record === 'object' && Object.keys(record).length > 0) {
2821
+ hasAnyData = true;
2822
+ console.log(`AmplifyModelService: Record ${i} has data:`, Object.keys(record));
2823
+ break;
2824
2824
  }
2825
2825
  }
2826
- // Strategy 4: Very permissive validation - if we have ANY records with ANY relationship data, consider it valid
2827
- // This is to handle cases where the relationship structure is different than expected
2828
- const totalValidRecords = Math.max(populatedCount + partiallyPopulatedCount, recordsWithAnyRelationshipData);
2829
- console.log(`AmplifyModelService: Relationship validation summary:`, {
2830
- fieldName: config.fieldName,
2831
- totalRecords: records.length,
2832
- populatedCount,
2833
- partiallyPopulatedCount,
2834
- recordsWithAnyRelationshipData,
2835
- totalValidRecords,
2836
- validationPassed: totalValidRecords > 0
2837
- });
2838
- if (totalValidRecords === 0) {
2839
- // Log very detailed information about what we found
2840
- const sampleRecord = records[0];
2841
- const detailedError = {
2842
- method: 'validateRelationshipFieldPopulation',
2843
- recordCount: records.length,
2844
- populatedCount,
2845
- partiallyPopulatedCount,
2846
- recordsWithAnyRelationshipData,
2847
- fieldName: config.fieldName,
2848
- sampleRecord: sampleRecord ? {
2849
- keys: Object.keys(sampleRecord),
2850
- values: sampleRecord,
2851
- fieldValue: sampleRecord[config.fieldName],
2852
- fieldType: typeof sampleRecord[config.fieldName]
2853
- } : null,
2854
- allRecordKeys: records.map((r) => r ? Object.keys(r) : []),
2855
- config: {
2856
- relationshipModelName: config.relationshipModelName,
2857
- baseModelName: config.baseModelName,
2858
- fieldName: config.fieldName,
2859
- associatedWith: config.associatedWith
2860
- }
2861
- };
2862
- this.errorHandler.logSelectionSetError(SelectionSetErrorType.FIELD_NOT_FOUND, `No records have relationship field '${config.fieldName}' populated - detailed analysis shows no relationship data found`, config, undefined, detailedError);
2863
- console.error(`AmplifyModelService: DETAILED VALIDATION FAILURE for field '${config.fieldName}':`, detailedError);
2864
- // TEMPORARY: For debugging, let's be even more permissive and return true if we have any records at all
2865
- // This will help us see what data is actually being processed
2866
- if (records.length > 0) {
2867
- console.warn(`AmplifyModelService: TEMPORARY DEBUG MODE - Allowing validation to pass despite no relationship data found`);
2868
- return true;
2869
- }
2826
+ if (!hasAnyData) {
2827
+ console.warn('AmplifyModelService: No valid records found in query result');
2870
2828
  return false;
2871
2829
  }
2872
- console.log(`AmplifyModelService: Relationship field validation SUCCESSFUL: ${totalValidRecords}/${records.length} records have some form of relationship data for '${config.fieldName}' field`);
2830
+ console.log(`AmplifyModelService: Relationship validation successful - found ${records.length} records with data`);
2873
2831
  return true;
2874
2832
  }
2875
2833
  catch (error) {
2876
- this.errorHandler.logSelectionSetError(SelectionSetErrorType.GRAPHQL_ERROR, `Error validating relationship field population: ${error instanceof Error ? error.message : String(error)}`, config, undefined, {
2877
- method: 'validateRelationshipFieldPopulation',
2878
- originalError: {
2879
- message: error instanceof Error ? error.message : String(error),
2880
- stack: error instanceof Error ? error.stack : undefined
2881
- }
2882
- });
2883
2834
  console.error('AmplifyModelService: Error validating relationship field population:', error);
2884
- // In case of validation error, be permissive and return true to avoid blocking the UI
2885
- console.warn('AmplifyModelService: Validation error occurred, allowing relationship to proceed');
2835
+ // Be permissive on validation errors
2886
2836
  return true;
2887
2837
  }
2888
2838
  }
2889
- /**
2890
- * Check if a record has nested relationship data based on field patterns
2891
- * This helps validate cases where selection sets use nested field access like "table.id", "table.name"
2892
- */
2893
- hasNestedRelationshipData(record, fieldName) {
2894
- if (!record || typeof record !== 'object') {
2895
- return false;
2896
- }
2897
- // Look for any fields that start with the relationship field name followed by a dot
2898
- const nestedFieldPattern = `${fieldName}.`;
2899
- for (const key of Object.keys(record)) {
2900
- if (key.startsWith(nestedFieldPattern)) {
2901
- const value = record[key];
2902
- if (value !== undefined && value !== null) {
2903
- console.log(`AmplifyModelService: Found nested relationship data: ${key} = ${value}`);
2904
- return true;
2905
- }
2906
- }
2907
- }
2908
- return false;
2909
- }
2910
- /**
2911
- * Check if a record has any field that might be related to the relationship field
2912
- * This is a very permissive check for debugging purposes
2913
- */
2914
- hasAnyRelatedField(record, fieldName) {
2915
- if (!record || typeof record !== 'object') {
2916
- return false;
2917
- }
2918
- const fieldNameLower = fieldName.toLowerCase();
2919
- for (const key of Object.keys(record)) {
2920
- const keyLower = key.toLowerCase();
2921
- // Check if the key contains the field name or vice versa
2922
- if (keyLower.includes(fieldNameLower) || fieldNameLower.includes(keyLower)) {
2923
- const value = record[key];
2924
- if (value !== undefined && value !== null) {
2925
- console.log(`AmplifyModelService: Found potentially related field: ${key} = ${value}`);
2926
- return true;
2927
- }
2928
- }
2929
- }
2930
- return false;
2931
- }
2932
2839
  /**
2933
2840
  * Log query attempt details
2934
2841
  */