mirror of
https://gitlab.com/comunic/comunicmobile
synced 2024-11-29 08:16:28 +00:00
78 lines
2.4 KiB
Dart
78 lines
2.4 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:comunic/helpers/account_credentials_helper.dart';
|
|
import 'package:comunic/models/api_request.dart';
|
|
import 'package:comunic/models/api_response.dart';
|
|
import 'package:comunic/models/config.dart';
|
|
import 'package:dio/dio.dart';
|
|
|
|
/// API Helper
|
|
///
|
|
/// @author Pierre HUBERT
|
|
|
|
class APIHelper {
|
|
/// Execute a [request] on the server and returns a [APIResponse]
|
|
///
|
|
/// This method should never throw but the response code of the [APIResponse]
|
|
/// should be verified before accessing response content
|
|
Future<APIResponse> exec(APIRequest request, {bool multipart = false}) async {
|
|
try {
|
|
//Add API tokens
|
|
request.addString("serviceName", config().serviceName);
|
|
request.addString("serviceToken", config().serviceToken);
|
|
|
|
//Add user tokens (if required)
|
|
if (request.needLogin) {
|
|
final tokens = await AccountCredentialsHelper().get();
|
|
assert(tokens != null);
|
|
request.addString("userToken1", tokens.tokenOne);
|
|
request.addString("userToken2", tokens.tokenTwo);
|
|
}
|
|
|
|
// Determine server URL
|
|
final path = config().apiServerUri + request.uri;
|
|
Uri url;
|
|
if (!config().apiServerSecure)
|
|
url = Uri.http(config().apiServerName, path);
|
|
else
|
|
url = Uri.https(config().apiServerName, path);
|
|
|
|
final data = FormData.from(request.args);
|
|
|
|
// Process files (if required)
|
|
if (multipart)
|
|
request.files.forEach(
|
|
(k, v) => data.add(k, UploadFileInfo(v, v.path.split("/").last)));
|
|
|
|
// Execute the request
|
|
final response = await Dio().post(
|
|
url.toString(),
|
|
data: data,
|
|
options: Options(
|
|
receiveDataWhenStatusError: true,
|
|
validateStatus: (s) => true,
|
|
responseType: ResponseType.plain,
|
|
),
|
|
);
|
|
|
|
if (response.statusCode != HttpStatus.ok)
|
|
return APIResponse(response.statusCode, null);
|
|
|
|
return APIResponse(response.statusCode, response.data);
|
|
} on Exception catch (e) {
|
|
print(e.toString());
|
|
print("Could not execute a request!");
|
|
return APIResponse(-1, null);
|
|
} on DioError catch(e){
|
|
print(e.toString());
|
|
print("Could not execute a request (Dio error)!");
|
|
return APIResponse(-1, null);
|
|
}
|
|
}
|
|
|
|
/// Same as exec, but also allows to send files
|
|
Future<APIResponse> execWithFiles(APIRequest request) async {
|
|
return await exec(request, multipart: true);
|
|
}
|
|
}
|