示例工程 ch16-bookmarks

ch16-bookmarks/lib/src/data/remote_api.dart

dart · 1.9 KB

// 数据层(二):远程 API。
//
// 只做一件事:HTTP → 领域草稿(BookmarkDraft)。错误统一翻译成 SyncException。
import 'dart:async';
import 'dart:convert';
 
import 'package:http/http.dart' as http;
 
import '../core/config.dart';
import '../domain/bookmark.dart';
import '../domain/bookmark_repository.dart';
 
class HttpBookmarkRemoteApi implements BookmarkRemoteApi {
  HttpBookmarkRemoteApi({required this.client, required this.config});
 
  final http.Client client;
  final AppConfig config;
 
  @override
  Future<List<BookmarkDraft>> fetchDrafts({int limit = 10}) async {
    final Uri uri = Uri.parse('${config.baseUrl}/posts?_limit=$limit');
    try {
      final http.Response response = await client
          .get(uri, headers: <String, String>{'Accept': 'application/json'})
          .timeout(config.requestTimeout);
 
      if (response.statusCode < 200 || response.statusCode >= 300) {
        throw SyncException('服务器返回 ${response.statusCode}');
      }
      final Object? decoded = jsonDecode(utf8.decode(response.bodyBytes));
      if (decoded is! List<Object?>) {
        throw const SyncException('响应格式错误:期望数组');
      }
      return <BookmarkDraft>[
        for (final Object? raw in decoded)
          if (raw is Map<String, Object?>)
            BookmarkDraft(
              title: (raw['title'] as String? ?? '无标题').trim(),
              url: 'https://jsonplaceholder.typicode.com/posts/${raw['id']}',
              note: (raw['body'] as String? ?? '').trim(),
            ),
      ];
    } on SyncException {
      rethrow;
    } on TimeoutException catch (e) {
      throw SyncException('同步超时,请稍后重试', cause: e);
    } on FormatException catch (e) {
      throw SyncException('响应不是合法 JSON', cause: e);
    } on Exception catch (e) {
      throw SyncException('网络不可用:$e', cause: e);
    }
  }
}