apiRequestObject<T> static method

Future<void> apiRequestObject<T>({
  1. required BuildContext context,
  2. required SuccessCallback onSuccess,
  3. required FailureCallback onFailure,
  4. String additionalUrlParams = '',
  5. Map<String, String> headers = const {'Content-Type' : 'application/json'},
  6. Map<String, dynamic> bodyParams = const {},
  7. Map<String, dynamic> uriParameter = const {},
  8. required String endpoint,
  9. required HTTPMethod httpMethod,
  10. dynamic successParser(
    1. Map<String, dynamic> json
    )?,
  11. bool showLoading = true,
})

Implementation

static Future<void> apiRequestObject<T>({
  ///[context] is used to show the Loading Widget.
  required BuildContext context,

  ///[registryName] is the registryName user has passed in the
  ///ApiRegistryModel while registering a Api.
  //required String registryName,

  ///[onSuccess] Callback is called in state of Success.
  required SuccessCallback onSuccess,

  ///[onFailure] Callback is called in state of Failure.
  required FailureCallback onFailure,

  ///[additionalUrlParams] are the parameters appended after the endpoint.
  String additionalUrlParams = '',

  ///[headers] that the user wants to pass to the api.
  Map<String, String> headers = const {'Content-Type': 'application/json'},

  ///[bodyParams] are the params the user wants to pass to the api.
  Map<String, dynamic> bodyParams = const {},
  //dynamic binaryBody,

  ///[uriParameter] are appended after the [additionalUrlParams] in case if
  ///[additionalUrlParams] are empty [uriParameter] are appended to the
  ///endpoint.
  Map<String, dynamic> uriParameter = const {},

  ///[endpoint] of the api.
  required String endpoint,

  ///[httpMethod] type of api i.e post, get, put, delete.
  required HTTPMethod httpMethod,

  ///[successParser] is used parse the response into model response i.e
  ///nothing but fromJson function of the model.
  dynamic Function(Map<String, dynamic> json)? successParser,

  ///[showLoading] can be used to turn on or off loading.
  bool showLoading = true,
}) async {
  final headerBody = headers;
  final body = (bodyParams.isNotEmpty ? jsonEncode(bodyParams) : null);
  late http.Response response;
  dynamic jsonResponse;
  //bool isOnline = true;

  ///It will throw the exception if developer has not registered for it.
  // if (_registeredApis
  //     .where((element) => element.registryName == registryName)
  //     .isEmpty) {
  //   throw Exception('Please register the api first');
  // }

  // final currentApi = _registeredApis
  //     .where((element) => element.registryName == registryName)
  //     .toList()
  //     .first;

  var url = _baseUrl! +
      (endpoint.endsWith('/')
          ? endpoint.substring(0, endpoint.length - 1)
          : endpoint) +
      (additionalUrlParams.isEmpty
          ? ''
          : (additionalUrlParams.startsWith('/')
              ? additionalUrlParams
              : "/$additionalUrlParams"));

  url = _appendUrlParams(url, uriParameter);
  //bool isOnline = await Utility().isInternet();

  // try {
  // final result = await InternetAddress.lookup('example.com');
  // if (result.isNotEmpty && result[0].rawAddress.isNotEmpty && isOnline) {
  //   dPrint('Internet connected');
  try {
    if (showLoading) {
      _showLoader(context);
    }
    if (httpMethod == HTTPMethod.get) {
      response = await _client.get(Uri.parse(url), headers: headerBody);
    } else if (httpMethod == HTTPMethod.put) {
      response =
          await _client.put(Uri.parse(url), headers: headerBody, body: body);
    } else if (httpMethod == HTTPMethod.delete) {
      response = await _client.delete(Uri.parse(url), headers: headerBody);
    } else if (httpMethod == HTTPMethod.post) {
      response =
          await _client.post(Uri.parse(url), headers: headerBody, body: body);
    } else {
      if (showLoading) {
        if (_showLoadingWidget) {
          Navigator.pop(context);
        }
      }
    }

    dPrint("---------------------API START----------------------------");
    dPrint("url 📶 $httpMethod -> $url");
    dPrint("headers ➡️ ${headerBody["Authorization"]}");
    dPrint("body params ➡️ $body");
    dPrint("uri params ➡️ $uriParameter");
    dPrint(" Response (${response.statusCode}) - ${(response.body)}");
    dPrint("---------------------API END-------------------------------");

    if (response.statusCode == 200 || response.statusCode == 201) {
      if (_statusCheckKey != null && _statusValues.isEmpty) {
        throw Exception('Please enter status values in Api Config');
      }
      if (_statusValues.isNotEmpty && _statusCheckKey == null) {
        throw Exception('Please enter statusCodeKey in Api Config');
      }
      try {
        jsonResponse = json.decode(response.body);
      } catch (e) {
        onSuccess(response.body);
        if (showLoading) {
          if (_showLoadingWidget) {
            if (context.mounted) {
              Navigator.pop(context);
            }
          }
        }
        return;
      }
      if (_statusCheckKey != null && _statusValues.isNotEmpty) {
        if (jsonResponse is Map<String, dynamic>) {
          if (_statusValues
              .where((element) => element == jsonResponse[_statusCheckKey])
              .isNotEmpty) {
            ///Success Case
            if (successParser != null) {
              onSuccess(successParser(jsonResponse));
            } else {
              onSuccess(jsonResponse);
            }
            if (showLoading) {
              if (_showLoadingWidget) {
                if (context.mounted) {
                  Navigator.pop(context);
                }
              }
            }
            return;
          } else {
            ///Failure Case execution
            dPrint('Api Error');
            if (_failureParser != null) {
              onFailure(_failureParser!(jsonResponse), response.statusCode);
            } else {
              onFailure(jsonResponse, response.statusCode);
            }
            _showErrorToastMethod(jsonResponse);
            if (showLoading) {
              if (_showLoadingWidget) {
                if (context.mounted) {
                  Navigator.pop(context);
                }
              }
            }
            return;
          }
        } else if (jsonResponse is List<dynamic>) {
          // onSuccess(currentApi.listOfSuccessConstructor == null
          //     ? jsonResponse
          //     : currentApi.listOfSuccessConstructor!(jsonResponse
          //         .map((e) => e as Map<String, dynamic>)
          //         .toList()));
          if (successParser != null) {
            final List jsonList =
                jsonResponse.map((e) => successParser(e)).toList();
            onSuccess(jsonList);
          } else {
            onSuccess(jsonResponse);
          }
          if (showLoading) {
            if (_showLoadingWidget) {
              if (context.mounted) {
                Navigator.pop(context);
              }
            }
          }
          return;
        }
      }
      if (jsonResponse is Map<String, dynamic>) {
        if (successParser != null) {
          onSuccess(successParser(jsonResponse));
        } else {
          onSuccess(jsonResponse);
        }
        if (showLoading) {
          if (_showLoadingWidget) {
            if (context.mounted) {
              Navigator.pop(context);
            }
          }
        }
        return;
      } else if (jsonResponse is List<dynamic>) {
        if (successParser != null) {
          final List jsonList =
              jsonResponse.map((e) => successParser(e)).toList();
          onSuccess(jsonList);
        } else {
          onSuccess(jsonResponse);
        }

        if (showLoading) {
          if (_showLoadingWidget) {
            if (context.mounted) {
              Navigator.pop(context);
            }
          }
        }
        return;
      }
    } else if (response.statusCode == 401) {
      if (_failureParser != null) {
        onFailure(
            _failureParser!(jsonDecode(response.body)), response.statusCode);
      } else {
        onFailure(jsonDecode(response.body), response.statusCode);
      }
      _showErrorToastMethod(jsonDecode(response.body));
      if (showLoading) {
        if (_showLoadingWidget) {
          if (context.mounted) {
            Navigator.pop(context);
          }
        }
      }
      if (_unauthorizedFn != null) {
        if (context.mounted) {
          _unauthorizedFn!(context);
        }
      }
    } else {
      if (_failureParser != null) {
        onFailure(
            _failureParser!(jsonDecode(response.body)), response.statusCode);
      } else {
        onFailure(jsonDecode(response.body), response.statusCode);
      }
      _showErrorToastMethod(jsonDecode(response.body));
      if (showLoading) {
        if (_showLoadingWidget) {
          if (context.mounted) {
            Navigator.pop(context);
          }
        }
      }
    }
  } on SocketException catch (e) {
    // EasyLoading.showError("No internet connection!");
    if (showLoading) {
      if (_showLoadingWidget) {
        Navigator.pop(context);
      }
    }
    dPrint(
        "address: ${e.address},  message: ${e.message},osError: ${e.osError},port: ${e.port}");
    final error = NoInternet(e.message.toString());

    onFailure(error, response.statusCode);
    _showToast('Please connect to internet');
  } on Exception catch (exception) {
    /// only executed if error is of type Exception
    if (showLoading) {
      if (_showLoadingWidget) {
        Navigator.pop(context);
      }
    }
    final error = FetchDataError(exception.toString());
    onFailure(error, response.statusCode);
    if (response.body.isNotEmpty) {
      _showErrorToastMethod(jsonDecode(response.body));
    }
  } catch (e, s) {
    if (showLoading) {
      if (_showLoadingWidget) {
        Navigator.pop(context);
      }
    }
    dPrint('Catch ${e.toString()}');
    dPrint(s.toString());
    // executed for errors of all types other than Exception
    final error = FetchDataError(e.toString());
    onFailure(error, response.statusCode);
    if (response.body.isNotEmpty) {
      _showErrorToastMethod(jsonDecode(response.body));
    }
    // }
    //}
  }
}