Files
recipe-app/flutter/lib/features/pantry/data/pantry_repository.dart
T
Nils-Johan Gynther e7251fd94c
Test Suite / test (24.15.0) (push) Has been cancelled
feat: add location field to PantryItem model and update related functionality
Co-authored-by: Copilot <copilot@github.com>
2026-05-06 11:54:56 +02:00

74 lines
2.2 KiB
Dart

import 'package:logging/logging.dart';
import '../../../core/api/api_client.dart';
import '../../../core/api/api_paths.dart';
import '../domain/pantry_item.dart';
import '../domain/pantry_product.dart';
final _logger = Logger('PantryRepository');
class PantryRepository {
final ApiClient _api;
const PantryRepository(this._api);
Future<List<PantryItem>> fetchPantry({String? token}) async {
try {
final data = await _api.getJson(PantryApiPaths.list, token: token);
final list = data as List<dynamic>;
_logger.info('Fetched ${list.length} pantry items');
return list
.map((e) => PantryItem.fromJson(e as Map<String, dynamic>))
.toList();
} catch (error) {
_logger.severe('Failed to fetch pantry items: $error');
rethrow;
}
}
Future<List<PantryProduct>> fetchProducts({String? token}) async {
try {
final data = await _api.getJson(ProductApiPaths.mine, token: token);
final list = data as List<dynamic>;
_logger.info('Fetched ${list.length} products');
return list
.map((e) => PantryProduct.fromJson(e as Map<String, dynamic>))
.toList();
} catch (error) {
_logger.severe('Failed to fetch products: $error');
rethrow;
}
}
Future<PantryItem> createPantryItem(
int productId, {
String? token,
String? location,
}) async {
try {
final data = await _api.postJson(
PantryApiPaths.list,
body: {
'productId': productId,
if (location != null && location.trim().isNotEmpty)
'location': location.trim(),
},
token: token,
);
_logger.info('Created pantry item for product ID: $productId');
return PantryItem.fromJson(data as Map<String, dynamic>);
} catch (error) {
_logger.severe('Failed to create pantry item: $error');
rethrow;
}
}
Future<void> deletePantryItem(int id, {String? token}) async {
try {
await _api.deleteJson(PantryApiPaths.remove(id), token: token);
_logger.info('Deleted pantry item with ID: $id');
} catch (error) {
_logger.severe('Failed to delete pantry item: $error');
rethrow;
}
}
}