fetchById method
Reads a single entity by id using a DataFetchStrategy.
Implementation
Future<T?> fetchById(
String id, {
DataFetchStrategy strategy = DataFetchStrategy.localFirst,
String? userId,
List<String> withRelated = const [],
bool persistRemoteResults = false,
}) async {
_ensureInitialized();
Future<T?> readLocal() => read(id, userId: userId, withRelated: withRelated);
Future<T?> readRemote() => remoteAdapter.read(id, userId: userId);
switch (strategy) {
case DataFetchStrategy.localOnly:
return readLocal();
case DataFetchStrategy.remoteOnly:
return readRemote();
case DataFetchStrategy.localFirst:
final local = await readLocal();
if (local != null) return local;
final remote = await readRemote();
if (persistRemoteResults && remote != null) {
await _persistFetchedLocally([remote]);
}
return remote;
case DataFetchStrategy.remoteFirst:
try {
final remote = await readRemote();
if (remote != null) {
if (persistRemoteResults) await _persistFetchedLocally([remote]);
return remote;
}
return await readLocal();
} catch (e) {
_logger.warn('remoteFirst read failed, falling back to local: $e');
return readLocal();
}
}
}