57 lines
1.8 KiB
Dart
57 lines
1.8 KiB
Dart
import 'dart:developer';
|
|||
|
|
|
||
|
|
import 'package:dartz/dartz.dart';
|
||
|
|
import 'package:injectable/injectable.dart';
|
||
|
|
|
||
|
|
import '../../../domain/unit/unit.dart';
|
||
|
|
import '../datasources/local_data_provider.dart';
|
||
|
|
import '../datasources/remote_data_provider.dart';
|
||
|
|
|
||
|
|
@Injectable(as: IUnitRepository)
|
||
|
|
class UnitRepository implements IUnitRepository {
|
||
|
|
final UnitRemoteDataProvider _remoteDataProvider;
|
||
|
|
final UnitLocalDataProvider _localDataProvider;
|
||
|
|
|
||
|
|
final _logName = 'UnitRepository';
|
||
|
|
|
||
|
|
UnitRepository(this._remoteDataProvider, this._localDataProvider);
|
||
|
|
|
||
|
|
@override
|
||
|
|
Future<Either<UnitFailure, List<ProductUnit>>> getUnits({
|
||
|
|
bool forceRefresh = false,
|
||
|
|
}) async {
|
||
|
|
try {
|
||
|
|
final cached = _localDataProvider.getUnits();
|
||
|
|
|
||
|
|
if (!forceRefresh && cached.isNotEmpty) {
|
||
|
|
log('📏 ${cached.length} satuan dari cache', name: _logName);
|
||
|
|
return right(cached.map((e) => e.toDomain()).toList());
|
||
|
|
}
|
||
|
|
|
||
|
|
final result = await _remoteDataProvider.fetchUnits();
|
||
|
|
|
||
|
|
if (result.hasError) {
|
||
|
|
// Offline bukan alasan untuk kehilangan satuan yang sudah pernah ada.
|
||
|
|
if (cached.isNotEmpty) {
|
||
|
|
log('⚠️ Gagal ambil satuan, pakai cache', name: _logName);
|
||
|
|
return right(cached.map((e) => e.toDomain()).toList());
|
||
|
|
}
|
||
|
|
return left(result.error!);
|
||
|
|
}
|
||
|
|
|
||
|
|
final units = result.data!;
|
||
|
|
await _localDataProvider.saveUnits(units);
|
||
|
|
|
||
|
|
log('✅ ${units.length} satuan disinkronkan', name: _logName);
|
||
|
|
return right(units.map((e) => e.toDomain()).toList());
|
||
|
|
} catch (e, s) {
|
||
|
|
log('❌ Error getUnits', name: _logName, error: e, stackTrace: s);
|
||
|
|
return left(UnitFailure.localStorageError(e.toString()));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
@override
|
||
|
|
Future<List<ProductUnit>> cachedUnits() async =>
|
||
|
|
_localDataProvider.getUnits().map((e) => e.toDomain()).toList();
|
||
|
|
}
|