makeRequest method

Future<Response> makeRequest({
  1. dynamic endpoint,
  2. required RequestMethods method,
  3. Map? params,
})

Implementation

Future<Response> makeRequest({
  endpoint,
  required RequestMethods method,
  Map<dynamic, dynamic>? params,
}) async {
  if (Avanda.config.rootUrl == null) {
    throw "Specify the server root URL in Avanda.setConfig() function";
  }

  http.Response httpResponse;

  params = stringifyPayload(params);

  endpoint = Avanda.config.rootUrl! + '?query=' + endpoint;

  try {
    switch (method) {
      case RequestMethods.get:
        httpResponse = await http.get(
          Uri.parse(endpoint),
          headers: headers,
        );
        break;
      case RequestMethods.post:
        httpResponse = await http.post(
          Uri.parse(endpoint),
          headers: headers,
          body: params,
        );
        break;
      case RequestMethods.delete:
        httpResponse = await http.delete(
          Uri.parse(endpoint),
          headers: headers,
          body: params,
        );
        break;
    }
  } catch (e) {
    throw InternetNetworkError(
        ResponseStruct.fromJson({'msg': e.toString()}));
  }
  if (Avanda.config.debugMode) {
    print(httpResponse.body);
  }

  var response = ResponseStruct.fromJson(jsonDecode(httpResponse.body));

  Map<int, RequestException> errors = {
    404: FileNotFoundError(response),
    400: BadRequestError(response),
    500: InternalServerError(response),
    403: AccessForbiddenError(response),
    401: UnauthorizedAccess(response),
    405: MethodNotAllowedError(response),
    0: InternetNetworkError(response),
  };

  if (errors.containsKey(response.status) &&
      (response.status ?? 500) >= 300) {
    throw errors[response.status] ?? UnknownError(response);
  }

  return Response(response);
}