delete<T> method

Future<Response<T>> delete<T>(
  1. Map<String, dynamic> params, {
  2. required FromJsonFactory<T> fromJsonFactory,
  3. void callback(
    1. RazorpayApiException?,
    2. Response<T>?
    )?,
})

Implementation

Future<Response<T>> delete<T>(
  Map<String, dynamic> params, {
  required FromJsonFactory<T> fromJsonFactory,
  void Function(RazorpayApiException?, Response<T>?)? callback,
}) async {
  try {
    // Make the DELETE request
    final rawResponse = await client.delete<dynamic>(
      // Expect dynamic data
      getEntityUrl(params),
    );

    T resultData;
    final data = rawResponse.data;

    // The FromJsonFactory expects Map<String, dynamic>.
    if (data == null || (data is Map && data.isEmpty)) {
      // Handle null or empty map response.
      // Assume the factory can handle null or {} if T is designed for it (e.g., nullable).
      try {
        // If data is null, pass null. If data is {}, pass {}. Cast needed for type safety.
        resultData = fromJsonFactory(data as Map<String, dynamic>? ?? {});
      } catch (e, s) {
        throw FormatException(
          'Failed to construct type $T from null or empty map response body. Check fromJson for $T. Status: ${rawResponse.statusCode}. Error: $e\n$s',
          data,
        );
      }
    } else if (data is Map<String, dynamic>) {
      // Handle non-empty map response
      resultData = fromJsonFactory(data);
    } else if (data is List) {
      // The factory expects a Map, but received a List.
      throw FormatException(
        'Unexpected List response format for DELETE request to ${getEntityUrl(params)}. Expected Map<String, dynamic> for FromJsonFactory<$T>. Status: ${rawResponse.statusCode}',
        data,
      );
    } else {
      // Handle other unexpected response data formats
      throw FormatException(
        'Unexpected response data type (${data.runtimeType}) for DELETE request to ${getEntityUrl(params)}. Expected Map<String, dynamic>. Status: ${rawResponse.statusCode}',
      );
    }

    final typedResponse = Response<T>(
      data: resultData,
      requestOptions: rawResponse.requestOptions,
      statusCode: rawResponse.statusCode,
      statusMessage: rawResponse.statusMessage,
      isRedirect: rawResponse.isRedirect,
      redirects: rawResponse.redirects,
      extra: rawResponse.extra,
      headers: rawResponse.headers,
    );

    callback?.call(null, typedResponse);
    return typedResponse;
  } on DioException catch (error) {
    final normalizedError = _normalizeError(error);
    callback?.call(normalizedError, null);
    throw normalizedError;
  } catch (error) {
    final exception =
        RazorpayApiException(message: 'An unexpected error occurred: $error');
    callback?.call(exception, null);
    throw exception;
  }
}