This repository has been archived on 2025-08-25. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
Seshat/lib/data/repositories/owner_repository.dart
2025-08-15 12:51:36 +02:00

86 lines
2.1 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;
Owner? _sectionOwner;
Future<Result<Owner>> get sectionOwner async {
if (_sectionOwner != null) {
return Result.ok(_sectionOwner!);
}
final result = await _apiClient.getSectionOwner();
switch (result) {
case Ok():
_sectionOwner = result.value;
break;
default:
break;
}
return result;
}
Future<Result<Owner>> getOwnerById(int id) async {
if (_cachedOwners != null) {
final result1 = _cachedOwners!
.where((owner) => owner.id == id)
.firstOrNull;
if (result1 != null) {
return Result.ok(result1);
}
}
return await _apiClient.getOwnerById(id);
}
/// 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();
}
}