call method

Future<Response> call({
  1. required String? endpoint,
  2. required Method method,
  3. Map<String, dynamic> body = const {},
  4. List<Map<String, dynamic>> files = const [],
})

Implementation

Future<http.Response> call({
  required String? endpoint,
  required Method method,
  Map<String, dynamic> body = const {},
  List<Map<String, dynamic>> files = const [],
}) async {
  try {
    final token = MorniService.token;
    final baseURL = MorniService.baseUrl;
    final lang = MorniService.language;
    late http.Response response;

    if (token == null) {
      throw Exception('Token is missing or invalid.');
    }

    if (baseURL == null) {
      throw Exception('baseURL is missing or invalid.');
    }

    final headers = {
      'Content-Type': files.isNotEmpty ? 'multipart/form-data' : 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $token',
      'accept-language': lang.toString(),
    };

    Uri uri = Uri.parse('$baseURL/api/$endpoint');
    if (method == Method.GET) {
      final queryParameters = {
        ...body.map((k, v) => MapEntry(k, v.toString())),
      };
      uri = uri.replace(queryParameters: queryParameters);
    }

    if (files.isNotEmpty) {

      var request = http.MultipartRequest(method.toApiString, uri);
      request.headers.addAll(headers);

      for (var fileData in files) {
        File file = fileData['file'];
        String key = fileData['key'];
        request.files.add(await http.MultipartFile.fromPath(key, file.path));
      }

      if (body.isNotEmpty) {
        body.forEach((key, value) {
          request.fields[key] = value.toString();
        });
      }

      var streamedResponse = await request.send();
      return await http.Response.fromStream(streamedResponse);
    }

    String? encodedBody;

    if (body.isNotEmpty) {
      encodedBody = json.encode(body);
    }

    switch (method) {
      case Method.GET:
        response = await http.get(uri, headers: headers);
        break;
      case Method.POST:
        response = await http.post(uri, headers: headers, body: encodedBody);
        break;
      case Method.PUT:
        response = await http.put(uri, headers: headers, body: encodedBody);
        break;
      case Method.DELETE:
        response = await http.delete(
          uri,
          headers: headers,
          body: encodedBody,
        );
      default:
        throw UnsupportedError('Method $method not supported');
    }
    return response;
  } catch (e) {
    throw Exception(e);
  }
}