parseApiResponse static method

MockAPIResponse parseApiResponse(
  1. Map<String, dynamic> map, {
  2. required String sourceLabel,
  3. required String apiName,
})

Implementation

static MockAPIResponse parseApiResponse(
  Map<String, dynamic> map, {
  required String sourceLabel,
  required String apiName,
}) {
  if (map.isEmpty) {
    throw EnsembleTestFailure(
      'API mock "$apiName" in "$sourceLabel" must include a response',
    );
  }
  if (map.containsKey(mergeKey) || map.containsKey(extendsKey)) {
    throw EnsembleTestFailure(
      'API mock "$apiName" in "$sourceLabel" still contains unresolved '
      '$extendsKey/$mergeKey keys.',
    );
  }
  final unknownKeys = map.keys
      .where(
        (key) => !const {
          'statusCode',
          'body',
          'headers',
          'delayMs',
          'responses',
        }.contains(key),
      )
      .toList();
  if (unknownKeys.isNotEmpty) {
    throw EnsembleTestFailure(
      'API mock "$apiName" in "$sourceLabel" has unsupported keys: '
      '${unknownKeys.join(", ")}. Use direct JSON shape or $mergeKey paths.',
    );
  }

  final responses = map['responses'];
  if (responses != null) {
    if (responses is! List || responses.isEmpty) {
      throw EnsembleTestFailure(
        'API mock "$apiName" in "$sourceLabel" responses must be a non-empty list',
      );
    }
    return MockAPIResponse(
      responses: [
        for (final entry in responses)
          if (entry is Map)
            parseApiResponse(
              _stringifyKeys(Map<dynamic, dynamic>.from(entry)),
              sourceLabel: sourceLabel,
              apiName: apiName,
            )
          else
            throw EnsembleTestFailure(
              'API mock "$apiName" in "$sourceLabel" responses entries must be objects',
            ),
      ],
    );
  }

  return MockAPIResponse(
    statusCode: map['statusCode'] as int? ?? 200,
    body: map.containsKey('body') ? deepCopy(map['body']) : null,
    headers: map['headers'] is Map
        ? Map<String, dynamic>.from(deepCopy(map['headers']) as Map)
        : null,
    delayMs: map['delayMs'] as int?,
  );
}