postFormData method

Future<Map<String, dynamic>> postFormData(
  1. String endpoint,
  2. FormData formData, {
  3. Map<String, String>? queryParams,
})

Make a POST request with form data and return JSON response (for STT)

Implementation

Future<Map<String, dynamic>> postFormData(
  String endpoint,
  FormData formData, {
  Map<String, String>? queryParams,
}) async {
  try {
    final response = await _dio.post(
      endpoint,
      data: formData,
      queryParameters: queryParams,
      options: Options(headers: {'xi-api-key': config.apiKey}),
    );

    if (response.statusCode != 200) {
      throw ProviderError(
        'ElevenLabs STT API returned status ${response.statusCode}',
      );
    }

    // Handle both JSON and string responses like original implementation
    final responseData = response.data;
    if (responseData is Map<String, dynamic>) {
      return responseData;
    } else if (responseData is String) {
      // Try to parse as JSON if it's a string
      try {
        final Map<String, dynamic> parsed = {};
        // For simple text responses, wrap in a text field
        parsed['text'] = responseData;
        return parsed;
      } catch (e) {
        throw ResponseFormatError(
          'Failed to parse ElevenLabs STT response: $e',
          responseData,
        );
      }
    } else {
      return responseData as Map<String, dynamic>;
    }
  } on DioException catch (e) {
    throw DioErrorHandler.handleDioError(e, 'ElevenLabs');
  } catch (e) {
    if (e is LLMError) rethrow;
    throw GenericError('Unexpected error: $e');
  }
}