This repository has been archived on 2026-06-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
FabledApp/lib/data/api/api_client.dart
T
bvandeusen 7df7b5ff85 feat(offline): tier 2 phase 3 — write queue with optimistic UI
Offline writes now queue + apply optimistically instead of throwing.
On reconnect, the queue drains automatically; conflicts and rejections
surface as one-time SnackBars so the user knows their edit didn't land.

- Drift schema v3: `pending_writes` table (verb + payload + baseline +
  tries + last_error). Negative ids serve as cache placeholders for
  offline-created rows until replay assigns the server id.
- Each write repository (notes, tasks, projects, milestones, events)
  now catches NetworkException, applies the change to cache (with a
  fresh `nextTempId()` for creates), and enqueues the API call.
- Edits to a still-queued offline-created row coalesce into the
  original create payload — only one server call per row, in order.
- Deletes of still-queued offline-created rows drop the queue entry
  and the cache row; no server call ever happens.
- New WriteQueue service drains the queue oldest-first.
  Server-wins on `updated_at` baseline check (notes/tasks/projects);
  last-writer-wins for milestones/events (no getOne available).
  4xx → drop + surface as `rejected`; conflict → drop + `overwritten`;
  404 on update → drop + `missing`; 5xx/network → keep + retry next
  online cycle.
- Replay fires on AuthStatus → authenticated transitions
  (cold-start, came-back-online, login).
- OfflineBanner shows "Retry (N)" with the pending-writes count.
- Distinct ServerException added so 4xx no longer masquerade as
  NetworkException — the queue can drop them instead of looping.

flutter analyze clean; 21 tests pass (3 new for QueueFailure messaging).
Phase 4 (read-only UI indicators on cached/temp rows) still ahead.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-28 22:08:40 -04:00

84 lines
2.6 KiB
Dart

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import '../../core/exceptions.dart';
PersistCookieJar buildCookieJar(String cookiesPath) =>
PersistCookieJar(storage: FileStorage('$cookiesPath/.cookies/'));
Dio buildDio(String baseUrl, PersistCookieJar cookieJar) {
final dio = Dio(BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 30),
headers: {'Content-Type': 'application/json'},
));
dio.interceptors.add(CookieManager(cookieJar));
dio.interceptors.add(_ErrorInterceptor());
return dio;
}
class _ErrorInterceptor extends Interceptor {
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
if (err.response?.statusCode == 401) {
handler.reject(DioException(
requestOptions: err.requestOptions,
error: const AuthException('Session expired. Please log in again.'),
type: err.type,
response: err.response,
));
return;
}
if (err.type == DioExceptionType.connectionTimeout ||
err.type == DioExceptionType.connectionError) {
handler.reject(DioException(
requestOptions: err.requestOptions,
error: const NetworkException('Cannot reach server. Check your connection.'),
type: err.type,
response: err.response,
));
return;
}
if (err.type == DioExceptionType.receiveTimeout ||
err.type == DioExceptionType.sendTimeout) {
handler.reject(DioException(
requestOptions: err.requestOptions,
error: const AppException('Request timed out. The server is taking too long to respond.'),
type: err.type,
response: err.response,
));
return;
}
handler.next(err);
}
}
AppException dioToApp(DioException e) {
if (e.error is AppException) return e.error as AppException;
final status = e.response?.statusCode;
if (status == 401) return const AuthException('Not authenticated.');
if (status == 404) return const NotFoundException('Resource not found.');
if (status != null && status >= 400) {
final msg = _extractServerErrorMessage(e.response) ??
'Request failed (HTTP $status).';
return ServerException(msg, status);
}
return NetworkException(e.message ?? 'Unknown network error.');
}
String? _extractServerErrorMessage(Response? resp) {
final data = resp?.data;
if (data is Map<String, dynamic>) {
for (final key in const ['detail', 'error', 'message']) {
final value = data[key];
if (value is String && value.isNotEmpty) return value;
}
}
return null;
}