parseResponse<T> static method

T parseResponse<T>({
  1. required Object? object,
  2. required BaseServiceRequestParams params,
})

Parses a response object into a result of type T.

Handles various input types, including strings, maps, lists, and bytes, performing necessary conversions or JSON decoding.

Throws: RPCError if parsing fails.

Returns: The parsed response as an object of type T.

Implementation

static T parseResponse<T>(
    {required Object? object, required BaseServiceRequestParams params}) {
  try {
    if (object is T) return object;
    if (object == null && null is T) {
      return null as T;
    }
    if (dynamic is T) {
      return object as T;
    }
    if (<String, dynamic>{} is T) {
      if (object is Map) return object.cast<String, dynamic>() as T;
      if (object is String) {
        return StringUtils.toJson<Map<String, dynamic>>(object) as T;
      }
    }
    if (<Map<String, dynamic>>[] is T) {
      if (object is String) {
        return StringUtils.toJson<List>(object)
            .map((e) => (e as Map).cast<String, dynamic>())
            .toList() as T;
      }
      return (object as List)
          .map((e) => (e as Map).cast<String, dynamic>())
          .toList() as T;
    }
    if (<int>[] is T) {
      if (object is List<int>) {
        return StringUtils.encode(object as String) as T;
      }
      return (Object as List).cast<int>() as T;
    }
    return object as T;
  } catch (e) {
    throw RPCError(
        message: "Parsing response failed.",
        request: params.toJson(),
        details: {"error": e.toString()});
  }
}