send<T> method

Future<APIResponse<T>> send<T>(
  1. String target,
  2. RequestType type, {
  3. Map<String, dynamic>? data,
  4. List<MultipartFile> files = const [],
  5. dynamic onFilesUpload(
    1. int bytes,
    2. int totalBytes
    )?,
  6. bool log = false,
  7. Function? onNoConnection,
  8. Map<String, String> headers = const {},
  9. bool appendHeader = true,
  10. String errorsField = 'errors',
})

Implementation

Future<APIResponse<T>> send<T>(
  String target,
  RequestType type, {
  Map<String, dynamic>? data,
  List<http.MultipartFile> files = const [],
  Function(int bytes, int totalBytes)? onFilesUpload,
  bool log = false,
  Function? onNoConnection,
  Map<String, String> headers = const {},
  bool appendHeader = true,
  String errorsField = 'errors',
}) async {
  if (appendHeader) headers = {...headers, ...this.headers};
  String url = '$apiUrl/$target';
  if (log) {
    dev.log("[StorageDatabaseAPI] reqUrl: $url");
    dev.log("[StorageDatabaseAPI] reqHeaders: $headers");
  }
  String responseBody = '';
  int statusCode = 400;
  try {
    Uri uri = Uri.parse(url);
    if (files.isNotEmpty) {
      http.MultipartRequest request = MultipartRequest(
        type.type,
        Uri.parse(url),
        onProgress: onFilesUpload,
      );
      request.files.addAll(files);
      request.fields.addAll({
        for (String key in (data ?? {}).keys) key: data![key].toString(),
      });
      request.headers.addAll(headers);
      http.StreamedResponse res = await request.send();
      statusCode = res.statusCode;
      responseBody = await res.stream.bytesToString();
    } else {
      http.Response response;
      if (type == RequestType.post) {
        response = await http.post(
          uri,
          headers: headers,
          body: jsonEncode(data),
        );
      } else if (type == RequestType.put) {
        response = await http.put(
          uri,
          headers: headers,
          body: jsonEncode(data),
        );
      } else if (type == RequestType.patch) {
        response = await http.patch(
          uri,
          headers: headers,
          body: jsonEncode(data),
        );
      } else if (type == RequestType.delete) {
        response = await http.delete(
          uri,
          headers: headers,
          body: jsonEncode(data),
        );
      } else {
        response = await http.get(uri, headers: headers);
      }
      responseBody = response.body;
      statusCode = response.statusCode;
    }
    return APIResponse.fromResponse(
      responseBody,
      statusCode,
      log: log,
      errorsField: errorsField,
    );
  } on SocketException {
    if (onNoConnection != null) onNoConnection();
    if (log) dev.log("[StorageDatabaseAPI] reqError: No Internet Connection");
    return APIResponse<T>(false, "No Internet Connection", statusCode);
  } catch (e) {
    return APIResponse<T>(false, 'ExceptionError: $e', statusCode);
  }
}