runable
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import 'package:hive_ce/hive.dart';
|
||||
import '../models/product_model.dart';
|
||||
|
||||
/// Product local data source using Hive
|
||||
abstract class ProductLocalDataSource {
|
||||
Future<List<ProductModel>> getAllProducts();
|
||||
Future<ProductModel?> getProductById(String id);
|
||||
Future<void> cacheProducts(List<ProductModel> products);
|
||||
Future<void> clearProducts();
|
||||
}
|
||||
|
||||
class ProductLocalDataSourceImpl implements ProductLocalDataSource {
|
||||
final Box<ProductModel> box;
|
||||
|
||||
ProductLocalDataSourceImpl(this.box);
|
||||
|
||||
@override
|
||||
Future<List<ProductModel>> getAllProducts() async {
|
||||
return box.values.toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<ProductModel?> getProductById(String id) async {
|
||||
return box.get(id);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> cacheProducts(List<ProductModel> products) async {
|
||||
final productMap = {for (var p in products) p.id: p};
|
||||
await box.putAll(productMap);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearProducts() async {
|
||||
await box.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import '../models/product_model.dart';
|
||||
import '../../../../core/network/dio_client.dart';
|
||||
import '../../../../core/constants/api_constants.dart';
|
||||
|
||||
/// Product remote data source using API
|
||||
abstract class ProductRemoteDataSource {
|
||||
Future<List<ProductModel>> getAllProducts();
|
||||
Future<ProductModel> getProductById(String id);
|
||||
Future<List<ProductModel>> searchProducts(String query);
|
||||
}
|
||||
|
||||
class ProductRemoteDataSourceImpl implements ProductRemoteDataSource {
|
||||
final DioClient client;
|
||||
|
||||
ProductRemoteDataSourceImpl(this.client);
|
||||
|
||||
@override
|
||||
Future<List<ProductModel>> getAllProducts() async {
|
||||
final response = await client.get(ApiConstants.products);
|
||||
final List<dynamic> data = response.data['products'] ?? [];
|
||||
return data.map((json) => ProductModel.fromJson(json)).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<ProductModel> getProductById(String id) async {
|
||||
final response = await client.get(ApiConstants.productById(id));
|
||||
return ProductModel.fromJson(response.data);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<ProductModel>> searchProducts(String query) async {
|
||||
final response = await client.get(
|
||||
ApiConstants.searchProducts,
|
||||
queryParameters: {'q': query},
|
||||
);
|
||||
final List<dynamic> data = response.data['products'] ?? [];
|
||||
return data.map((json) => ProductModel.fromJson(json)).toList();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user