7fb9031f8d
CI / flutter-gates (push) Successful in 1m12s
- pet_models.dart:pets 域 DTO 逐字段对齐冻结契约(宠物/品种/体重/ 疫苗目录/疫苗/健康事件/照护提醒/聚合摘要 + cursor 分页信封), 枚举严格解析,请求体部分更新语义(缺席字段不出现) - pets_repository.dart:PetsRepository 抽象 + ApiPetsRepository, 12 路径 18 操作全覆盖;四个 POST 携带 Idempotency-Key; 复用既有 ApiClient token 拦截与单飞刷新重放 - pet_exceptions.dart:新 8 错误码映射为类型化异常 (40300/40401/40402/40902/40903/40904/42201/42202), 仍可按 ApiBusinessException 基类捕获 - pets_controller.dart:宠物档案状态自 AppState 拆出 (Controller → Repository → API Client 分层,四态就绪供 T2-12) - money.dart:元/分换算工具(DTO 层保持整数分,UI 层 T2-14 使用) - api_client.dart:新增 patbondPetApiBaseUrl(:8083,--dart-define 可覆盖)与 query 参数支持;api_exception.dart 补 pets 域错误码 - 测试 64 → 126:DTO 映射、错误类型化映射、请求线路 (路径/方法/鉴权/分页/幂等键/tz)、控制器状态机、金额换算 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
170 lines
5.3 KiB
Dart
170 lines
5.3 KiB
Dart
import 'package:dio/dio.dart';
|
|
import 'package:patbond_flutter/core/network/api_envelope.dart';
|
|
import 'package:patbond_flutter/core/network/api_exception.dart';
|
|
import 'package:patbond_flutter/core/network/token_refresher.dart';
|
|
import 'package:patbond_flutter/features/auth/session_manager.dart';
|
|
|
|
/// API 基地址:`--dart-define=PATBOND_API_BASE_URL=...` 注入,默认本机后端。
|
|
const String patbondApiBaseUrl = String.fromEnvironment(
|
|
'PATBOND_API_BASE_URL',
|
|
defaultValue: 'http://127.0.0.1:8081',
|
|
);
|
|
|
|
/// user 服务基地址(/api/v1/me、/api/v1/events):MVP 阶段 auth 与 user
|
|
/// 分端口直连(ADR-002 无网关),`--dart-define=PATBOND_USER_API_BASE_URL=...` 注入。
|
|
const String patbondUserApiBaseUrl = String.fromEnvironment(
|
|
'PATBOND_USER_API_BASE_URL',
|
|
defaultValue: 'http://127.0.0.1:8082',
|
|
);
|
|
|
|
/// pet 服务基地址(/api/v1/pets、/api/v1/breeds、/api/v1/vaccine-catalog 等
|
|
/// pets 域 12 路径):沿用 auth :8081 / user :8082 的分端口直连模式,
|
|
/// `--dart-define=PATBOND_PET_API_BASE_URL=...` 注入。
|
|
const String patbondPetApiBaseUrl = String.fromEnvironment(
|
|
'PATBOND_PET_API_BASE_URL',
|
|
defaultValue: 'http://127.0.0.1:8083',
|
|
);
|
|
|
|
/// 构建全局共用的 Dio 实例。
|
|
///
|
|
/// `validateStatus` 放行所有状态码:错误信封由 [ApiClient] 统一解析成
|
|
/// 类型化异常,不依赖 dio 的 4xx/5xx 抛错路径。
|
|
Dio buildPatbondDio({required SessionManager session, String? baseUrl}) {
|
|
final dio = Dio(
|
|
BaseOptions(
|
|
baseUrl: baseUrl ?? patbondApiBaseUrl,
|
|
connectTimeout: const Duration(seconds: 5),
|
|
sendTimeout: const Duration(seconds: 10),
|
|
receiveTimeout: const Duration(seconds: 10),
|
|
contentType: Headers.jsonContentType,
|
|
validateStatus: (_) => true,
|
|
),
|
|
);
|
|
dio.interceptors.add(AuthInterceptor(session));
|
|
return dio;
|
|
}
|
|
|
|
/// 鉴权拦截器:对标记 [ApiClient.requiresAuthExtra] 的请求附加
|
|
/// `Authorization: Bearer`,并统一携带设备标识。
|
|
class AuthInterceptor extends Interceptor {
|
|
AuthInterceptor(this._session);
|
|
|
|
final SessionManager _session;
|
|
|
|
@override
|
|
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
|
final deviceId = _session.deviceId;
|
|
if (deviceId != null) {
|
|
options.headers['X-Device-Id'] = deviceId;
|
|
}
|
|
if (options.extra[ApiClient.requiresAuthExtra] == true) {
|
|
final token = _session.accessToken;
|
|
if (token != null) {
|
|
options.headers['Authorization'] = 'Bearer $token';
|
|
}
|
|
}
|
|
handler.next(options);
|
|
}
|
|
}
|
|
|
|
/// HTTP 客户端封装:错误信封 → 类型化异常,401/40101 → 刷新后重放一次。
|
|
class ApiClient {
|
|
ApiClient({
|
|
required this._dio,
|
|
required this._session,
|
|
required this._refresher,
|
|
});
|
|
|
|
/// RequestOptions.extra 标记:该请求需要 Bearer 鉴权。
|
|
static const requiresAuthExtra = 'patbond.requiresAuth';
|
|
|
|
final Dio _dio;
|
|
final SessionManager _session;
|
|
final TokenRefresher _refresher;
|
|
|
|
/// 发起请求并返回信封中的 `data`。
|
|
///
|
|
/// 鉴权请求遇 HTTP 401 或 code 40101 时:经单飞刷新后原样重放一次;
|
|
/// 重放仍失败则清会话并抛 [SessionExpiredException]。
|
|
Future<Object?> request(
|
|
String path, {
|
|
String method = 'POST',
|
|
Object? body,
|
|
Map<String, Object?>? query,
|
|
Map<String, Object?>? headers,
|
|
bool requiresAuth = false,
|
|
}) async {
|
|
var response = await _send(
|
|
path,
|
|
method: method,
|
|
body: body,
|
|
query: query,
|
|
headers: headers,
|
|
requiresAuth: requiresAuth,
|
|
);
|
|
|
|
if (requiresAuth && _isAuthFailure(response)) {
|
|
await _refresher.refresh();
|
|
response = await _send(
|
|
path,
|
|
method: method,
|
|
body: body,
|
|
query: query,
|
|
headers: headers,
|
|
requiresAuth: requiresAuth,
|
|
);
|
|
if (_isAuthFailure(response)) {
|
|
await _session.clearSession();
|
|
throw const SessionExpiredException('刷新后重放仍未通过鉴权');
|
|
}
|
|
}
|
|
|
|
return _unwrap(response);
|
|
}
|
|
|
|
Future<Response<Object?>> _send(
|
|
String path, {
|
|
required String method,
|
|
required bool requiresAuth,
|
|
Object? body,
|
|
Map<String, Object?>? query,
|
|
Map<String, Object?>? headers,
|
|
}) async {
|
|
try {
|
|
return await _dio.request<Object?>(
|
|
path,
|
|
data: body,
|
|
queryParameters: query,
|
|
options: Options(
|
|
method: method,
|
|
headers: headers,
|
|
extra: {requiresAuthExtra: requiresAuth},
|
|
),
|
|
);
|
|
} on DioException catch (error) {
|
|
throw ApiNetworkException('请求失败:${error.type.name}');
|
|
}
|
|
}
|
|
|
|
bool _isAuthFailure(Response<Object?> response) {
|
|
if (response.statusCode == 401) return true;
|
|
return ApiEnvelope.tryParse(response.data)?.code ==
|
|
ApiCodes.accessTokenInvalid;
|
|
}
|
|
|
|
Object? _unwrap(Response<Object?> response) {
|
|
final status = response.statusCode ?? 0;
|
|
if (status == 429) {
|
|
throw const ApiRateLimitException();
|
|
}
|
|
final envelope = ApiEnvelope.tryParse(response.data);
|
|
if (envelope == null || status >= 500) {
|
|
throw ApiNetworkException('响应异常:HTTP $status');
|
|
}
|
|
if (envelope.code == ApiCodes.ok) {
|
|
return envelope.data;
|
|
}
|
|
throw ApiBusinessException(code: envelope.code, message: envelope.message);
|
|
}
|
|
}
|