|
| 1 | +import 'package:dio/dio.dart'; |
| 2 | +import '../../core/error/failures.dart'; |
| 3 | +import '../../core/network/api_client.dart'; |
| 4 | +import '../../domain/models/category.dart'; |
| 5 | +import '../../presentation/providers/auth_provider.dart'; |
| 6 | +import '../../presentation/states/auth_state.dart'; |
| 7 | +import 'package:flutter_riverpod/flutter_riverpod.dart'; |
| 8 | + |
| 9 | +abstract class CategoryRemoteDatasource { |
| 10 | + Future<CategoriesResponse> getAllCategories(); |
| 11 | +} |
| 12 | + |
| 13 | +class CategoryRemoteDatasourceImpl implements CategoryRemoteDatasource { |
| 14 | + final ApiClient apiClient; |
| 15 | + final Ref ref; |
| 16 | + |
| 17 | + CategoryRemoteDatasourceImpl(this.apiClient, this.ref); |
| 18 | + |
| 19 | + @override |
| 20 | + Future<CategoriesResponse> getAllCategories() async { |
| 21 | + try { |
| 22 | + // Check if the user is authenticated |
| 23 | + final authState = ref.read(authNotifierProvider); |
| 24 | + if (authState is! AuthSuccess) { |
| 25 | + throw ServerFailure( |
| 26 | + message: 'Authentication required to fetch categories', |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + // Get the access token |
| 31 | + final token = authState.response.tokens.accessToken; |
| 32 | + |
| 33 | + // Make the API request with the token |
| 34 | + final response = await apiClient.get( |
| 35 | + '/categories/all', |
| 36 | + options: Options( |
| 37 | + headers: { |
| 38 | + 'Authorization': 'Bearer $token', |
| 39 | + }, |
| 40 | + ), |
| 41 | + ); |
| 42 | + |
| 43 | + // Pass the direct response data to the fromJson method |
| 44 | + return CategoriesResponse.fromJson(response.data); |
| 45 | + } on DioException catch (e) { |
| 46 | + throw ServerFailure( |
| 47 | + message: e.message ?? 'An error occurred while fetching categories', |
| 48 | + code: e.response?.statusCode, |
| 49 | + ); |
| 50 | + } catch (e) { |
| 51 | + if (e is ServerFailure) { |
| 52 | + rethrow; |
| 53 | + } |
| 54 | + throw ServerFailure(message: e.toString()); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments