1
0
mirror of https://gitlab.com/comunic/comunicmobile synced 2024-11-23 05:19:22 +00:00
comunicmobile/lib/helpers/api_helper.dart

78 lines
2.4 KiB
Dart
Raw Normal View History

2019-04-22 17:16:26 +00:00
import 'dart:io';
2019-04-23 12:35:41 +00:00
import 'package:comunic/helpers/account_credentials_helper.dart';
2019-04-22 17:16:26 +00:00
import 'package:comunic/models/api_request.dart';
import 'package:comunic/models/api_response.dart';
import 'package:comunic/models/config.dart';
2019-04-25 18:14:19 +00:00
import 'package:dio/dio.dart';
2019-04-22 17:16:26 +00:00
/// 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
2019-04-25 18:14:19 +00:00
Future<APIResponse> exec(APIRequest request, {bool multipart = false}) async {
2019-04-22 17:16:26 +00:00
try {
//Add API tokens
request.addString("serviceName", config().serviceName);
request.addString("serviceToken", config().serviceToken);
//Add user tokens (if required)
2019-04-23 12:35:41 +00:00
if (request.needLogin) {
final tokens = await AccountCredentialsHelper().get();
assert(tokens != null);
request.addString("userToken1", tokens.tokenOne);
request.addString("userToken2", tokens.tokenTwo);
}
2019-04-22 17:16:26 +00:00
// 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);
2019-04-25 18:14:19 +00:00
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(
2019-04-25 09:44:58 +00:00
url.toString(),
2019-04-25 18:14:19 +00:00
data: data,
options: Options(
receiveDataWhenStatusError: true,
validateStatus: (s) => true,
responseType: ResponseType.plain,
),
2019-04-25 09:44:58 +00:00
);
2019-04-22 17:16:26 +00:00
if (response.statusCode != HttpStatus.ok)
return APIResponse(response.statusCode, null);
2019-04-25 18:14:19 +00:00
return APIResponse(response.statusCode, response.data);
2019-04-22 17:16:26 +00:00
} on Exception catch (e) {
print(e.toString());
print("Could not execute a request!");
return APIResponse(-1, null);
2019-04-27 07:29:38 +00:00
} on DioError catch(e){
print(e.toString());
print("Could not execute a request (Dio error)!");
return APIResponse(-1, null);
2019-04-22 17:16:26 +00:00
}
}
2019-04-25 18:14:19 +00:00
/// Same as exec, but also allows to send files
Future<APIResponse> execWithFiles(APIRequest request) async {
return await exec(request, multipart: true);
}
2019-04-22 17:16:26 +00:00
}