callApi method
Makes an API call with the specified endpoint, method, body, and file (optional). Returns the HTTP response from the API.
Implementation
Future<http.Response> callApi(
{required String? endpoint,
required String? method,
Map<String, dynamic> body = const {},
File? file,
int? page,
int? perPage,
bool? isSinaAPI = false}) async {
final token = AltibbiService.authToken;
final baseURL = isSinaAPI == true ? AltibbiService.sinaModelEndPointUrl : AltibbiService.url;
final lang = AltibbiService.lang;
if (token == null) {
throw Exception('Token is missing or invalid.');
}
final headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ${isSinaAPI == true ? "" : token}',
'accept-language': lang!
};
String? encodedBody;
Map<String, dynamic> requestBody = Map<String, dynamic>.from(body);
if (isSinaAPI == true) {
headers['partner-host'] = AltibbiService.url!;
headers['partner-user-token'] = token;
}
if (requestBody.isNotEmpty) {
encodedBody = json.encode(requestBody);
}
Uri url;
if (method == 'get') {
final queryParameters = Map.fromEntries(requestBody.entries
.map((entry) => MapEntry(entry.key, entry.value.toString())));
if (perPage != null && page != null) {
queryParameters['per-page'] = perPage.toString();
queryParameters['page'] = page.toString();
}
url = Uri.parse(baseURL!.contains("rest-api") ? baseURL : (isSinaAPI == true ? '$baseURL/$endpoint' : '$baseURL/v1/$endpoint'))
.replace(queryParameters: queryParameters);
} else {
url = Uri.parse(baseURL!.contains("rest-api") ? baseURL : (isSinaAPI == true ? '$baseURL/$endpoint' : '$baseURL/v1/$endpoint'));
if (method == 'post' && requestBody.containsKey('expand')) {
final expand = requestBody['expand'];
url = url.replace(queryParameters: {'expand': expand});
}
}
if (file != null) {
var request = http.MultipartRequest('POST', url);
request.headers.addAll(headers);
request.files.add(await http.MultipartFile.fromPath('file', file.path));
var streamedResponse = await request.send();
return await http.Response.fromStream(streamedResponse);
}
switch (method) {
case 'get':
return await http.get(url, headers: headers);
case 'post':
return await http.post(url, headers: headers, body: encodedBody);
case 'put':
return await http.put(url, headers: headers, body: encodedBody);
case 'delete':
return await http.delete(url, headers: headers, body: encodedBody);
default:
throw Exception('Invalid method type: $method');
}
}