示例工程 ch13-network

ch13-network/lib/src/posts_api.dart

dart · 7.1 KB

/// 基于 `package:http` 的 API 客户端:超时、重试、错误分类、流式下载。
///
/// 设计要点(正文 §13.3 详述):
///   1. 注入 `http.Client`(测试用 MockClient,生产用真实 client);
///   2. 所有异常都翻译成 `ApiException` 的子类;
///   3. 重试只对"可重试"错误(5xx / 429 / 网络 / 超时)做,指数退避;
///   4. 解析与传输分离:`Post.fromJson` 是纯函数。
library;
 
import 'dart:async';
import 'dart:convert';
import 'dart:io' show SocketException;
 
import 'package:http/http.dart' as http;
 
import 'api_exception.dart';
import 'post.dart';
 
class PostsApi {
  PostsApi({
    required this.client,
    this.baseUrl = 'https://jsonplaceholder.typicode.com',
    this.timeout = const Duration(seconds: 10),
    this.maxRetries = 2,
    this.retryDelay = const Duration(milliseconds: 200),
  });
 
  final http.Client client;
  final String baseUrl;
  final Duration timeout;
  final int maxRetries;
  final Duration retryDelay;
 
  /// 每个请求都带上的头。真实项目里鉴权 token 从这里注入(不要把 token 写死在代码里)。
  Map<String, String> headers = <String, String>{'Accept': 'application/json'};
 
  /// GET /posts?_limit=N
  Future<List<Post>> fetchPosts({int limit = 20}) async {
    final Object? body = await _getJson('/posts?_limit=$limit');
    if (body is! List<Object?>) {
      throw ParseException('期望数组,实际是 ${body.runtimeType}');
    }
    return <Post>[
      for (var i = 0; i < body.length; i++) _parsePost(body[i], index: i),
    ];
  }
 
  /// GET /posts/1
  Future<Post> fetchPost(int id) async {
    final Object? body = await _getJson('/posts/$id');
    if (body is! Map<String, Object?>) {
      throw ParseException('期望对象,实际是 ${body.runtimeType}');
    }
    try {
      return Post.fromJson(body);
    } on Object catch (e) {
      throw ParseException('文章解析失败', cause: e);
    }
  }
 
  /// POST /posts(返回服务器分配的 id)
  Future<int> createPost({required String title, required String body}) async {
    final http.Response response = await _sendWithRetry(
      () => client.post(
        _uri('/posts'),
        headers: <String, String>{...headers, 'Content-Type': 'application/json'},
        body: jsonEncode(<String, Object?>{'title': title, 'body': body, 'userId': 1}),
      ),
    );
    final Object? decoded = _decodeBody(response);
    if (decoded is! Map<String, Object?>) {
      throw const ParseException('创建响应不是对象');
    }
    return (decoded['id'] as num?)?.toInt() ?? 0;
  }
 
  /// PUT /posts/{id}:整体替换一条资源,返回服务器确认后的对象。
  Future<Post> replacePost({required int id, required String title, required String body}) async {
    final http.Response response = await _sendWithRetry(
      () => client.put(
        _uri('/posts/$id'),
        headers: <String, String>{...headers, 'Content-Type': 'application/json'},
        body: jsonEncode(<String, Object?>{'id': id, 'title': title, 'body': body, 'userId': 1}),
      ),
    );
    final Object? decoded = _decodeBody(response);
    if (decoded is! Map<String, Object?>) {
      throw const ParseException('替换响应不是对象');
    }
    return Post.fromJson(decoded);
  }
 
  /// DELETE /posts/{id}:成功时没有响应体(204 或 200)。
  Future<void> deletePost(int id) async {
    await _sendWithRetry(
      () => client.delete(_uri('/posts/$id'), headers: headers),
    );
  }
 
  /// 流式下载:`http.StreamedResponse` 的 stream 每来一块就回调一次进度。
  ///
  /// 对照 Go:`io.Copy` + `resp.Body`;对照 C:libcurl 的 `CURLOPT_WRITEFUNCTION` 回调。
  Future<List<int>> download(
    Uri uri, {
    void Function(int received, int? total)? onProgress,
    int? cancelAfterBytes,
  }) async {
    final http.StreamedResponse response = await client
        .send(http.Request('GET', uri))
        .timeout(timeout, onTimeout: () => throw const ApiTimeoutException('下载超时'));
 
    if (response.statusCode < 200 || response.statusCode >= 300) {
      throw HttpStatusException(response.statusCode, '');
    }
 
    final int? total = response.contentLength;
    final List<int> bytes = <int>[];
    await for (final List<int> chunk in response.stream) {
      bytes.addAll(chunk);
      onProgress?.call(bytes.length, total);
      // 演示"可中断的流式下载":不需要真的取消底层 socket,直接停止消费即可。
      if (cancelAfterBytes != null && bytes.length >= cancelAfterBytes) break;
    }
    return bytes;
  }
 
  void close() => client.close();
 
  // -------------------------------------------------------------------------
  // 内部实现
  // -------------------------------------------------------------------------
 
  Uri _uri(String path) => Uri.parse('$baseUrl$path');
 
  Post _parsePost(Object? raw, {required int index}) {
    if (raw is! Map<String, Object?>) {
      throw ParseException('第 $index 条记录不是对象');
    }
    try {
      return Post.fromJson(raw);
    } on Object catch (e) {
      throw ParseException('第 $index 条记录解析失败', cause: e);
    }
  }
 
  Future<Object?> _getJson(String path) async {
    final http.Response response = await _sendWithRetry(
      () => client.get(_uri(path), headers: headers),
    );
    return _decodeBody(response);
  }
 
  /// 重试 + 错误分类的唯一入口。
  Future<http.Response> _sendWithRetry(Future<http.Response> Function() request) async {
    var attempt = 0;
    while (true) {
      try {
        final http.Response response = await request().timeout(timeout);
        if (response.statusCode < 200 || response.statusCode >= 300) {
          final HttpStatusException error =
              HttpStatusException(response.statusCode, response.body);
          if (error.isRetryable && attempt < maxRetries) {
            await _backoff(attempt++);
            continue;
          }
          throw error;
        }
        return response;
      } on ApiException {
        rethrow;
      } on TimeoutException catch (e) {
        if (attempt < maxRetries) {
          await _backoff(attempt++);
          continue;
        }
        throw ApiTimeoutException('请求超时(${timeout.inSeconds}s)', cause: e);
      } on SocketException catch (e) {
        if (attempt < maxRetries) {
          await _backoff(attempt++);
          continue;
        }
        throw NetworkException(e.message, cause: e);
      } on http.ClientException catch (e) {
        if (attempt < maxRetries) {
          await _backoff(attempt++);
          continue;
        }
        throw NetworkException(e.message, cause: e);
      }
    }
  }
 
  Future<void> _backoff(int attempt) =>
      Future<void>.delayed(retryDelay * (1 << attempt)); // 200ms, 400ms, ...
 
  Object? _decodeBody(http.Response response) {
    try {
      // 用 bodyBytes + utf8.decode 而不是 response.body:
      // 后者按 Content-Type 猜编码,服务器给错 charset 时会乱码。
      return jsonDecode(utf8.decode(response.bodyBytes));
    } on FormatException catch (e) {
      throw ParseException('响应不是合法 JSON', cause: e);
    }
  }
}