58 lines
1.5 KiB
Dart
58 lines
1.5 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:seshat/data/services/api_client.dart';
|
|
import 'package:seshat/data/services/websocket_client.dart';
|
|
import 'package:seshat/domain/models/owner.dart';
|
|
import 'package:seshat/utils/result.dart';
|
|
|
|
class OwnerRepository {
|
|
OwnerRepository({
|
|
required ApiClient apiClient,
|
|
required WebsocketClient wsClient,
|
|
}) : _apiClient = apiClient,
|
|
_wsClient = wsClient;
|
|
|
|
final ApiClient _apiClient;
|
|
final WebsocketClient _wsClient;
|
|
late final StreamSubscription sub;
|
|
List<Owner>? _cachedOwners;
|
|
|
|
/// Adds an [Owner] to the database, and gets the resulting [Owner].
|
|
Future<Result<Owner>> addOwner(
|
|
String firstName,
|
|
String lastName,
|
|
String contact,
|
|
) async {
|
|
var response = await _apiClient.addOwner(firstName, lastName, contact);
|
|
switch (response) {
|
|
case Ok():
|
|
return Result.ok(response.value);
|
|
case Error():
|
|
return Result.error(response.error);
|
|
}
|
|
}
|
|
|
|
/// Fetches all the [Owner]s from the database, and subscribes to updates
|
|
Future<Result<List<Owner>>> getOwners() async {
|
|
if (_cachedOwners == null) {
|
|
final result = await _apiClient.getOwners();
|
|
_wsClient.connect();
|
|
|
|
if (result is Ok<List<Owner>>) {
|
|
_cachedOwners = result.value;
|
|
}
|
|
|
|
sub = _wsClient.owners.listen((owner) {
|
|
_cachedOwners!.add(owner);
|
|
});
|
|
|
|
return result;
|
|
} else {
|
|
return Result.ok(_cachedOwners!);
|
|
}
|
|
}
|
|
|
|
dispose() {
|
|
sub.cancel();
|
|
}
|
|
}
|