61 lines
2.0 KiB
Dart
61 lines
2.0 KiB
Dart
import 'package:dio/dio.dart';
|
|
import '../core/cache_manager.dart';
|
|
import '../core/constants/api_url.dart';
|
|
|
|
class ApiClient {
|
|
late final Dio dio;
|
|
|
|
ApiClient() {
|
|
dio = Dio(BaseOptions(
|
|
baseUrl: ApiUrl.baseUrl,
|
|
connectTimeout: const Duration(seconds: 30),
|
|
receiveTimeout: const Duration(seconds: 30),
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/json',
|
|
'Bypass-Tunnel-Reminder': 'true',
|
|
'ngrok-skip-browser-warning': 'true',
|
|
},
|
|
));
|
|
|
|
dio.interceptors.add(InterceptorsWrapper(
|
|
onRequest: (options, handler) async {
|
|
options.baseUrl = ApiUrl.baseUrl;
|
|
final token = CacheManager.authBox.get('auth_token');
|
|
if (token != null && token.isNotEmpty) {
|
|
options.headers['Authorization'] = 'Bearer $token';
|
|
}
|
|
return handler.next(options);
|
|
},
|
|
onResponse: (response, handler) {
|
|
// Deteksi response HTML (redirect ke login page — token expired)
|
|
final contentType = response.headers.value('content-type') ?? '';
|
|
final isHtml = contentType.contains('text/html') ||
|
|
(response.data is String &&
|
|
(response.data as String).trimLeft().startsWith('<!'));
|
|
|
|
if (isHtml) {
|
|
return handler.reject(
|
|
DioException(
|
|
requestOptions: response.requestOptions,
|
|
response: response,
|
|
type: DioExceptionType.badResponse,
|
|
error: 'Sesi habis atau server mengembalikan HTML.',
|
|
),
|
|
);
|
|
}
|
|
return handler.next(response);
|
|
},
|
|
onError: (DioException e, handler) {
|
|
// Cegah error "type 'String' is not a subtype of type 'int'" di repository
|
|
if (e.response != null && e.response!.data is String) {
|
|
e.response!.data = {
|
|
'message': 'Terjadi kesalahan server (${e.response!.statusCode}).',
|
|
};
|
|
}
|
|
return handler.next(e);
|
|
},
|
|
));
|
|
}
|
|
}
|