mergeApiMaps static method

void mergeApiMaps(
  1. Map<String, Map<String, dynamic>> target,
  2. Map<String, Map<String, dynamic>> incoming, {
  3. required String sourceLabel,
})

Merges incoming into target. Entries with $merge patch the existing API response; all other entries replace it.

Implementation

static void mergeApiMaps(
  Map<String, Map<String, dynamic>> target,
  Map<String, Map<String, dynamic>> incoming, {
  required String sourceLabel,
}) {
  for (final entry in incoming.entries) {
    final apiName = entry.key;
    final value = Map<String, dynamic>.from(entry.value);
    final merge = value.remove(mergeKey);
    if (merge == null) {
      target[apiName] = value;
      continue;
    }
    if (merge is! Map) {
      throw EnsembleTestFailure(
        'API mock "$apiName" in "$sourceLabel" $mergeKey must be a map of '
        'path → value.',
      );
    }
    final base = target[apiName];
    if (base == null) {
      throw EnsembleTestFailure(
        'API mock "$apiName" in "$sourceLabel" uses $mergeKey but there is '
        'no existing mock to patch. Add $extendsKey or a prior mock for this API.',
      );
    }
    final merged = deepCopy(base) as Map<String, dynamic>;
    // Non-merge keys on the same object replace those top-level fields first.
    for (final field in value.entries) {
      merged[field.key] = deepCopy(field.value);
    }
    applyMergePaths(
      merged,
      Map<String, dynamic>.from(merge),
      sourceLabel: sourceLabel,
      apiName: apiName,
    );
    target[apiName] = merged;
  }
}