mirror of
https://gitlab.com/comunic/comunicmobile
synced 2024-11-29 08:16:28 +00:00
58 lines
1.8 KiB
Dart
58 lines
1.8 KiB
Dart
import 'dart:convert';
|
|
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:http/http.dart' as http;
|
|
|
|
/// 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) 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 response = await http.post(
|
|
url.toString(),
|
|
body: request.args,
|
|
encoding: utf8
|
|
);
|
|
|
|
if (response.statusCode != HttpStatus.ok)
|
|
return APIResponse(response.statusCode, null);
|
|
|
|
return APIResponse(response.statusCode, utf8.decode(response.bodyBytes));
|
|
} on Exception catch (e) {
|
|
print(e.toString());
|
|
print("Could not execute a request!");
|
|
return APIResponse(-1, null);
|
|
}
|
|
}
|
|
}
|