request method

Future<ResponseModel> request({
  1. required String url,
  2. String? bearerToken,
  3. dynamic body,
  4. Map<String, dynamic>? queryParameters,
  5. RequestMethod requestMethod = RequestMethod.GET,
  6. bool authorize = false,
  7. bool expectJsonArray = false,
})

Implementation

Future<ResponseModel> request({
  required String url,
  String? bearerToken,
  dynamic body,
  Map<String, dynamic>? queryParameters,
  RequestMethod requestMethod = RequestMethod.GET,
  bool authorize = false,
  bool expectJsonArray = false,
}) async {
  var headers = <String, String>{};
  if (bearerToken != null && bearerToken.isNotEmpty) {
    headers[HttpHeaders.authorizationHeader] = 'Bearer $bearerToken';
  }
  if (requestMethod != RequestMethod.GET) {
    headers[HttpHeaders.contentTypeHeader] = 'application/json';
  }

  // URI ve query params
  var uri = Uri.parse(url);
  if (queryParameters != null && queryParameters.isNotEmpty) {
    uri = uri.replace(queryParameters: queryParameters);
  }

  var client = HttpClient();

  try {
    HttpClientRequest request = await _createRequest(client, requestMethod, uri);

    // Header'ları tek tek ekleyelim
    headers.forEach((key, value) {
      request.headers.set(key, value);
    });

    // Body'yi ekleyelim
    if (body != null && (requestMethod == RequestMethod.POST || requestMethod == RequestMethod.PUT || requestMethod == RequestMethod.PATCH)) {
      request.add(utf8.encode(json.encode(body)));
    }

    // Response'u alalım
    HttpClientResponse response = await request.close();

    // Yanıtı işle
    var responseBody = await response.transform(utf8.decoder).join();
    var jsonData = json.decode(responseBody);

    // Eğer array bekleniyorsa, kontrol yap
    if (expectJsonArray && jsonData is List) {
      return ResponseModel(
        data: jsonData,
        error: false,
        message: 'Success',
      );
    }

    // Eğer "data" varsa onu al, yoksa direkt jsonData
    var actualData = jsonData is Map<String, dynamic> && jsonData.containsKey('data') ? jsonData['data'] : jsonData;

    return ResponseModel(
      data: actualData,
      error: jsonData['error'] ?? false,
      message: jsonData['message'] ?? 'Success',
    );
  } catch (e) {
    return ResponseModel(
      data: null,
      error: true,
      message: e.toString(),
    );
  } finally {
    client.close();
  }
}