112 lines
2.5 KiB
Dart
112 lines
2.5 KiB
Dart
import 'package:dio/dio.dart';
|
|
import '../constants/api_constants.dart';
|
|
import 'api_interceptor.dart';
|
|
|
|
/// Dio HTTP client configuration
|
|
class DioClient {
|
|
late final Dio _dio;
|
|
String? _authToken;
|
|
|
|
DioClient() {
|
|
_dio = Dio(
|
|
BaseOptions(
|
|
baseUrl: ApiConstants.fullBaseUrl,
|
|
connectTimeout: Duration(milliseconds: ApiConstants.connectTimeout),
|
|
receiveTimeout: Duration(milliseconds: ApiConstants.receiveTimeout),
|
|
sendTimeout: Duration(milliseconds: ApiConstants.sendTimeout),
|
|
headers: {
|
|
ApiConstants.contentType: ApiConstants.applicationJson,
|
|
ApiConstants.accept: ApiConstants.applicationJson,
|
|
},
|
|
),
|
|
);
|
|
|
|
_dio.interceptors.add(ApiInterceptor());
|
|
|
|
// Add auth interceptor to inject token
|
|
_dio.interceptors.add(
|
|
InterceptorsWrapper(
|
|
onRequest: (options, handler) {
|
|
if (_authToken != null) {
|
|
options.headers[ApiConstants.authorization] = 'Bearer $_authToken';
|
|
}
|
|
return handler.next(options);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
Dio get dio => _dio;
|
|
|
|
/// Set authentication token for all future requests
|
|
void setAuthToken(String token) {
|
|
_authToken = token;
|
|
}
|
|
|
|
/// Clear authentication token
|
|
void clearAuthToken() {
|
|
_authToken = null;
|
|
}
|
|
|
|
/// Check if auth token is set
|
|
bool get hasAuthToken => _authToken != null;
|
|
|
|
/// GET request
|
|
Future<Response> get(
|
|
String path, {
|
|
Map<String, dynamic>? queryParameters,
|
|
Options? options,
|
|
}) async {
|
|
return await _dio.get(
|
|
path,
|
|
queryParameters: queryParameters,
|
|
options: options,
|
|
);
|
|
}
|
|
|
|
/// POST request
|
|
Future<Response> post(
|
|
String path, {
|
|
dynamic data,
|
|
Map<String, dynamic>? queryParameters,
|
|
Options? options,
|
|
}) async {
|
|
return await _dio.post(
|
|
path,
|
|
data: data,
|
|
queryParameters: queryParameters,
|
|
options: options,
|
|
);
|
|
}
|
|
|
|
/// PUT request
|
|
Future<Response> put(
|
|
String path, {
|
|
dynamic data,
|
|
Map<String, dynamic>? queryParameters,
|
|
Options? options,
|
|
}) async {
|
|
return await _dio.put(
|
|
path,
|
|
data: data,
|
|
queryParameters: queryParameters,
|
|
options: options,
|
|
);
|
|
}
|
|
|
|
/// DELETE request
|
|
Future<Response> delete(
|
|
String path, {
|
|
dynamic data,
|
|
Map<String, dynamic>? queryParameters,
|
|
Options? options,
|
|
}) async {
|
|
return await _dio.delete(
|
|
path,
|
|
data: data,
|
|
queryParameters: queryParameters,
|
|
options: options,
|
|
);
|
|
}
|
|
}
|