refactor(profile): update ProfileRepository to include Ref for improved state management and enhance error handling in tests
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import 'api_exception.dart';
|
||||
@@ -129,3 +130,7 @@ class ApiClient {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
final apiClientProvider = Provider<ApiClient>((ref) {
|
||||
return ApiClient();
|
||||
});
|
||||
|
||||
@@ -2,25 +2,29 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../../core/api/api_client.dart';
|
||||
import '../../../core/api/guarded_api_call.dart';
|
||||
import '../../../core/api/api_exception.dart';
|
||||
import '../../auth/data/auth_providers.dart';
|
||||
|
||||
final profileRepositoryProvider = Provider<ProfileRepository>((ref) {
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
return ProfileRepository(apiClient);
|
||||
return ProfileRepository(apiClient, ref);
|
||||
});
|
||||
|
||||
class ProfileRepository {
|
||||
final ApiClient _apiClient;
|
||||
final Ref _ref;
|
||||
|
||||
ProfileRepository(this._apiClient);
|
||||
ProfileRepository(this._apiClient, this._ref);
|
||||
|
||||
Future<Map<String, dynamic>> getProfile() async {
|
||||
return guardedApiCall(
|
||||
_ref,
|
||||
() => _apiClient.getJson('/api/profile'),
|
||||
);
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> updateProfile(Map<String, dynamic> profileData) async {
|
||||
return guardedApiCall(
|
||||
_ref,
|
||||
() => _apiClient.patchJson('/api/profile', profileData),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('should throw ApiException when API call fails', () async {
|
||||
when(mockApiClient.getJson('/api/profile')).thenThrow(ApiException('Failed to fetch profile'));
|
||||
when(mockApiClient.getJson('/api/profile')).thenThrow(ApiException(message: 'Failed to fetch profile'));
|
||||
|
||||
expect(() => profileRepository.getProfile(), throwsA(isA<ApiException>()));
|
||||
verify(mockApiClient.getJson('/api/profile')).called(1);
|
||||
@@ -49,7 +49,7 @@ void main() {
|
||||
|
||||
test('should throw ApiException when API call fails', () async {
|
||||
final profileData = {'username': 'newuser', 'email': 'new@example.com'};
|
||||
when(mockApiClient.patchJson('/api/profile', profileData)).thenThrow(ApiException('Failed to update profile'));
|
||||
when(mockApiClient.patchJson('/api/profile', profileData)).thenThrow(ApiException(message: 'Failed to update profile'));
|
||||
|
||||
expect(() => profileRepository.updateProfile(profileData), throwsA(isA<ApiException>()));
|
||||
verify(mockApiClient.patchJson('/api/profile', profileData)).called(1);
|
||||
|
||||
Reference in New Issue
Block a user