72 lines
2.2 KiB
Dart
72 lines
2.2 KiB
Dart
import 'package:dio/dio.dart';
|
||
import 'package:maibu_satabot_v2/core/consts/http_api_consts.dart';
|
||
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
|
||
import 'package:maibu_satabot_v2/core/di/injection.dart';
|
||
import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart';
|
||
|
||
class DioClient {
|
||
static Dio create() {
|
||
final dio = Dio(
|
||
BaseOptions(
|
||
baseUrl: HttpApiConsts.baseUrl,
|
||
connectTimeout: const Duration(seconds: 20),
|
||
receiveTimeout: const Duration(seconds: 20),
|
||
headers: {'Content-Type': 'application/json'},
|
||
),
|
||
);
|
||
|
||
dio.interceptors.add(
|
||
LogInterceptor(
|
||
requestBody: true,
|
||
responseBody: true,
|
||
requestHeader: true,
|
||
),
|
||
);
|
||
|
||
dio.interceptors.add(
|
||
InterceptorsWrapper(
|
||
onRequest: (options, handler) {
|
||
final userCubit = sl<AppUserCubit>();
|
||
final token = userCubit.state.user?.token;
|
||
|
||
if (token != null && token.isNotEmpty) {
|
||
options.headers['Authorization'] = 'Bearer $token';
|
||
}
|
||
|
||
return handler.next(options);
|
||
},
|
||
|
||
onResponse: (response, handler) {
|
||
if (response.data is Map<String, dynamic>) {
|
||
final code = response.data['code'];
|
||
if (code == 401 || code == 403) {
|
||
print(
|
||
'>>> [DIO] 🚨🚨🚨 收到业务错误码 $code,触发 Token 过期处理!URL: ${response.requestOptions.uri},时间: ${DateTime.now()}',
|
||
);
|
||
try {
|
||
sl<AuthCubit>().tokenExpired();
|
||
} catch (ex) {}
|
||
}
|
||
}
|
||
return handler.next(response);
|
||
},
|
||
|
||
onError: (DioException e, handler) async {
|
||
if (e.response?.statusCode == 401 || e.response?.statusCode == 403) {
|
||
print(
|
||
'>>> [DIO] 🚨🚨🚨 收到 HTTP ${e.response?.statusCode},触发 Token 过期处理!URL: ${e.requestOptions.uri},时间: ${DateTime.now()}',
|
||
);
|
||
try {
|
||
sl<AuthCubit>().tokenExpired();
|
||
} catch (ex) {}
|
||
}
|
||
|
||
return handler.next(e);
|
||
},
|
||
),
|
||
);
|
||
|
||
return dio;
|
||
}
|
||
}
|