feat(data-connect): Implement caching for business ID and enhance error handling in DataConnectService

This commit is contained in:
Achintha Isuru
2026-02-16 17:16:29 -05:00
parent d2cb05fe2e
commit fdd40ba72c
3 changed files with 154 additions and 147 deletions

View File

@@ -27,6 +27,9 @@ class DataConnectService with DataErrorHandler {
/// Cache for the current staff ID to avoid redundant lookups.
String? _cachedStaffId;
/// Cache for the current business ID to avoid redundant lookups.
String? _cachedBusinessId;
/// Gets the current staff ID from session store or persistent storage.
Future<String> getStaffId() async {
// 1. Check Session Store
@@ -41,15 +44,14 @@ class DataConnectService with DataErrorHandler {
// 3. Fetch from Data Connect using Firebase UID
final firebase_auth.User? user = _auth.currentUser;
if (user == null) {
throw Exception('User is not authenticated');
throw const NotAuthenticatedException(
technicalMessage: 'User is not authenticated',
);
}
try {
final fdc.QueryResult<
dc.GetStaffByUserIdData,
dc.GetStaffByUserIdVariables
>
response = await executeProtected(
final fdc.QueryResult<dc.GetStaffByUserIdData, dc.GetStaffByUserIdVariables>
response = await executeProtected(
() => connector.getStaffByUserId(userId: user.uid).execute(),
);
@@ -65,6 +67,30 @@ class DataConnectService with DataErrorHandler {
return user.uid;
}
/// Gets the current business ID from session store or persistent storage.
Future<String> getBusinessId() async {
// 1. Check Session Store
final dc.ClientSession? session = dc.ClientSessionStore.instance.session;
if (session?.business?.id != null) {
return session!.business!.id;
}
// 2. Check Cache
if (_cachedBusinessId != null) return _cachedBusinessId!;
// 3. Check Auth Status
final firebase_auth.User? user = _auth.currentUser;
if (user == null) {
throw const NotAuthenticatedException(
technicalMessage: 'User is not authenticated',
);
}
// 4. Fallback (should ideally not happen if DB is seeded and session is initialized)
// Ideally we'd have a getBusinessByUserId query here.
return user.uid;
}
/// Converts a Data Connect timestamp/string/json to a [DateTime].
DateTime? toDateTime(dynamic t) {
if (t == null) return null;
@@ -116,5 +142,6 @@ class DataConnectService with DataErrorHandler {
/// Clears the internal cache (e.g., on logout).
void clearCache() {
_cachedStaffId = null;
_cachedBusinessId = null;
}
}