feat: refactor code
This commit is contained in:
@@ -1,27 +0,0 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../config.dart';
|
||||
import '../storage/token_storage.dart';
|
||||
|
||||
/// کلاینت HTTP با تزریق خودکار توکن Bearer.
|
||||
class ApiClient {
|
||||
final Dio dio;
|
||||
|
||||
ApiClient(TokenStorage storage)
|
||||
: dio = Dio(BaseOptions(
|
||||
baseUrl: AppConfig.apiUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(seconds: 10),
|
||||
headers: {'Accept': 'application/json'},
|
||||
)) {
|
||||
dio.interceptors.add(InterceptorsWrapper(
|
||||
onRequest: (options, handler) async {
|
||||
final token = await storage.read();
|
||||
if (token != null && token.isNotEmpty) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
handler.next(options);
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../config.dart';
|
||||
import '../storage/token_storage.dart';
|
||||
|
||||
/// لایهی پایهی شبکه: یک Dio با baseUrl، تزریق خودکار توکن Bearer و
|
||||
/// validateStatus باز (تا کدهای خطا throw نشوند و در repository بررسی شوند).
|
||||
class ApiProviderImp {
|
||||
final Dio dio;
|
||||
|
||||
ApiProviderImp(TokenStorage storage)
|
||||
: dio = Dio(BaseOptions(
|
||||
baseUrl: AppConfig.apiUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(seconds: 15),
|
||||
headers: {'Accept': 'application/json'},
|
||||
validateStatus: (_) => true,
|
||||
)) {
|
||||
dio.interceptors.add(InterceptorsWrapper(
|
||||
onRequest: (options, handler) async {
|
||||
final token = await storage.read();
|
||||
if (token != null && token.isNotEmpty) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
handler.next(options);
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
Future<Response> get(String path, {Map<String, dynamic>? query}) =>
|
||||
dio.get(path, queryParameters: query);
|
||||
|
||||
Future<Response> post(String path, {Object? body}) =>
|
||||
dio.post(path, data: body);
|
||||
|
||||
Future<Response> put(String path, {Object? body}) =>
|
||||
dio.put(path, data: body);
|
||||
|
||||
Future<Response> delete(String path, {Object? body}) =>
|
||||
dio.delete(path, data: body);
|
||||
}
|
||||
Reference in New Issue
Block a user