send<T> method
Future<APIResponse<T>>
send<
T>( - String target,
- RequestType type, {
- Map<String, dynamic>? data,
- List<MultipartFile> files = const [],
- dynamic onFilesUpload(
- int bytes,
- int totalBytes
)?,
- bool log = false,
- Function? onNoConnection,
- 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);
}
}