92 lines
2.5 KiB
Dart
92 lines
2.5 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
import 'package:http/http.dart';
|
|
import 'package:seshat/config/constants.dart';
|
|
import 'package:seshat/domain/models/owner.dart';
|
|
import 'package:seshat/utils/command.dart';
|
|
import 'package:seshat/utils/result.dart';
|
|
|
|
typedef AuthHeaderProvider = String? Function();
|
|
|
|
class ApiClient {
|
|
ApiClient({String? host, int? port});
|
|
|
|
late final Command0 load;
|
|
String? token;
|
|
bool isReady = false;
|
|
FlutterSecureStorage? _secureStorage;
|
|
|
|
Future<void> _initStore() async {
|
|
_secureStorage ??= const FlutterSecureStorage(
|
|
aOptions: AndroidOptions(encryptedSharedPreferences: true),
|
|
);
|
|
}
|
|
|
|
/*
|
|
* ====================
|
|
* =====[ OWNERS ]=====
|
|
* ====================
|
|
*/
|
|
|
|
Future<Result<List<Owner>>> getOwners() async {
|
|
final client = Client();
|
|
try {
|
|
await _initStore();
|
|
final token = await _secureStorage!.read(key: "token");
|
|
final headers = {"Authorization": "Bearer $token"};
|
|
final response = await client.get(
|
|
Uri.parse("https://$apiBasePath/owners"),
|
|
headers: headers,
|
|
);
|
|
if (response.statusCode == 200) {
|
|
final json = jsonDecode(response.body) as List<dynamic>;
|
|
return Result.ok(
|
|
json.map((element) => Owner.fromJSON(element)).toList(),
|
|
);
|
|
} else {
|
|
return Result.error(Exception("Invalid request"));
|
|
}
|
|
} on Exception catch (error) {
|
|
return Result.error(error);
|
|
} finally {
|
|
client.close();
|
|
}
|
|
}
|
|
|
|
Future<Result<Owner>> addOwner(
|
|
String firstName,
|
|
String lastName,
|
|
String contact,
|
|
) async {
|
|
final client = Client();
|
|
try {
|
|
await _initStore();
|
|
final token = await _secureStorage!.read(key: "token");
|
|
final headers = {
|
|
"Authorization": "Bearer $token",
|
|
"Content-Type": "application/json",
|
|
};
|
|
final body = {
|
|
"first_name": firstName,
|
|
"last_name": lastName,
|
|
"contact": contact,
|
|
};
|
|
final response = await client.post(
|
|
Uri.parse("https://$apiBasePath/owner"),
|
|
headers: headers,
|
|
body: jsonEncode(body),
|
|
);
|
|
if (response.statusCode == 201) {
|
|
final json = jsonDecode(response.body);
|
|
return Result.ok(Owner.fromJSON(json));
|
|
} else {
|
|
return Result.error(Exception("Invalid request"));
|
|
}
|
|
} on Exception catch (error) {
|
|
return Result.error(error);
|
|
} finally {
|
|
client.close();
|
|
}
|
|
}
|
|
}
|