feat: cache the user profile information for performance
This commit is contained in:
parent
0c7298e626
commit
5870b29a9b
@ -6,6 +6,7 @@ import '../constants/api_constants.dart';
|
||||
class AuthService {
|
||||
static const FlutterSecureStorage _storage = FlutterSecureStorage();
|
||||
static const String _tokenKey = 'jwt_token';
|
||||
static const String _userDataKey = 'user_data';
|
||||
|
||||
static Future<Map<String, dynamic>> login(
|
||||
String emailOrUsername,
|
||||
@ -60,6 +61,7 @@ class AuthService {
|
||||
|
||||
static Future<void> logout() async {
|
||||
await _storage.delete(key: _tokenKey);
|
||||
await _storage.delete(key: _userDataKey);
|
||||
}
|
||||
|
||||
static Future<Map<String, String>> getAuthHeaders() async {
|
||||
@ -69,4 +71,20 @@ class AuthService {
|
||||
if (token != null) 'Authorization': 'Bearer $token',
|
||||
};
|
||||
}
|
||||
|
||||
static Future<void> saveUserData(Map<String, dynamic> userData) async {
|
||||
await _storage.write(key: _userDataKey, value: jsonEncode(userData));
|
||||
}
|
||||
|
||||
static Future<Map<String, dynamic>?> getCachedUserData() async {
|
||||
final userData = await _storage.read(key: _userDataKey);
|
||||
if (userData != null) {
|
||||
return jsonDecode(userData);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static Future<void> clearUserData() async {
|
||||
await _storage.delete(key: _userDataKey);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,14 +1,23 @@
|
||||
import 'dart:convert';
|
||||
import '../constants/api_constants.dart';
|
||||
import 'http_service.dart';
|
||||
import 'auth_service.dart';
|
||||
|
||||
class UserService {
|
||||
static Future<Map<String, dynamic>> getCurrentUser() async {
|
||||
static Future<Map<String, dynamic>> getCurrentUser({bool forceRefresh = false}) async {
|
||||
if (!forceRefresh) {
|
||||
final cachedData = await AuthService.getCachedUserData();
|
||||
if (cachedData != null) {
|
||||
return {'success': true, 'data': cachedData};
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
final response = await HttpService.get(ApiConstants.getUserEndpoint);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
await AuthService.saveUserData(data);
|
||||
return {'success': true, 'data': data};
|
||||
} else if (response.statusCode == 401) {
|
||||
return {'success': false, 'message': 'Session expired. Please login again.'};
|
||||
|
||||
Loading…
Reference in New Issue
Block a user