sendRequest<E> method

Future<Either<ApiFailure, E>> sendRequest<E>(
  1. String url,
  2. dynamic body,
  3. E fromJsonE(
    1. dynamic
    ),
  4. RequestType type, {
  5. Map<String, String>? headers,
  6. Map<String, String>? queryParams,
})

Implementation

Future<Either<ApiFailure, E>> sendRequest<E>(
  String url,
  dynamic body,
  E Function(dynamic) fromJsonE,
  RequestType type, {
  Map<String, String>? headers,
  Map<String, String>? queryParams,
}) async {
  try {
    final headers = await _getHeader(type);

    Uri uri = Uri.parse(url);

    if (queryParams != null) {
      uri = uri.replace(queryParameters: queryParams);
    }
    debugPrint('REQ URL : ${uri.toString()}');
    debugPrint('HEADERS : ${headers.toString()}');
    debugPrint('BODY : ${body.toString()}');

    var response = switch (type) {
      RequestType.GET => await client.get(uri, headers: headers),
      RequestType.POST => await client.post(
        uri,
        body: jsonEncode(body),
        headers: headers,
      ),
      RequestType.FORM_DATA_POST => await client.post(
        uri,
        body: body,
        headers: headers,
      ),
      RequestType.PATCH => await client.patch(uri, body: jsonEncode(body)),
      RequestType.PUT => await client.put(
        uri,
        body: jsonEncode(body),
        headers: headers,
      ),
      RequestType.DELETE => await client.delete(uri, headers: headers),
    };
    debugPrint('REQ -> ${url}');
    debugPrint('RESP CODE : ${response.statusCode.toString()}');
    dynamic decodedJson = response.body.isNotEmpty
        ? jsonDecode(response.body)
        : null;

    debugPrint('RESP -> ${decodedJson?.toString()}');
    if (response.statusCode >= 200 && response.statusCode < 300) {
      final responseObj = fromJsonE(decodedJson ?? {});
      return Right(responseObj);
    } else {
      return Left(
        ApiFailure.serverError(
          message: consolidateErrorMessages(decodedJson),
        ),
      );
    }
  } catch (e) {
    debugPrint('<>e $url :${e.toString()}');
    if (e is SocketException) {
      return const Left(
        ApiFailure.clientError(message: 'Failed to connect to server.'),
      );
    }
    return const Left(
      ApiFailure.clientError(message: 'An unknown error occurred.!'),
    );
  }
}