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

95 lines
2.4 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';
/// Repository to manage [Owner]
class OwnerRepository {
OwnerRepository({
required ApiClient apiClient,
required WebsocketClient wsClient,
}) : _apiClient = apiClient,
_wsClient = wsClient;
final ApiClient _apiClient;
final WebsocketClient _wsClient;
/// [StreamSubscription] to the [Stream<Owner>] for [_wsClient]
late final StreamSubscription sub;
/// [List<Owner>] of owners, updated by [_wsClient]
List<Owner>? _cachedOwners;
/// [Owner] of the current user
Owner? _ownerOfUser;
/// [Owner] of the current user
Future<Result<Owner>> get ownerOfUser async {
if (_ownerOfUser != null) {
return Result.ok(_ownerOfUser!);
}
final result = await _apiClient.getOwnerOfUser();
switch (result) {
case Ok():
_ownerOfUser = result.value;
break;
default:
break;
}
return result;
}
/// Gets an [Owner] from its [ownerId]
Future<Result<Owner>> getOwnerById(int ownerId) async {
if (_cachedOwners != null) {
final result1 = _cachedOwners!
.where((owner) => owner.id == ownerId)
.firstOrNull;
if (result1 != null) {
return Result.ok(result1);
}
}
return await _apiClient.getOwnerById(ownerId);
}
/// 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();
}
}