2023-07-04 11:51:11 +08:00
|
|
|
import 'package:dio/dio.dart';
|
|
|
|
|
2023-07-17 01:00:16 +08:00
|
|
|
import 'package:together_mobile/models/init_get_it.dart';
|
|
|
|
import 'package:together_mobile/models/token_model.dart';
|
|
|
|
|
2023-08-01 10:01:08 +08:00
|
|
|
const baseUrl = 'http://10.0.2.2:8000/api';
|
2023-09-09 16:48:47 +08:00
|
|
|
const userAvatarsUrl = 'http://10.0.2.2:8000/static/avatars/user';
|
|
|
|
const groupChatAvatarsUrl = 'http://10.0.2.2:8000/static/avatars/group_chat';
|
2023-08-01 10:01:08 +08:00
|
|
|
|
2023-07-04 11:51:11 +08:00
|
|
|
final baseOptions = BaseOptions(
|
2023-08-01 10:01:08 +08:00
|
|
|
baseUrl: baseUrl,
|
2023-07-04 11:51:11 +08:00
|
|
|
connectTimeout: const Duration(seconds: 5),
|
|
|
|
receiveTimeout: const Duration(seconds: 5),
|
|
|
|
);
|
|
|
|
|
|
|
|
var request = Dio(baseOptions)
|
|
|
|
..interceptors.add(
|
|
|
|
InterceptorsWrapper(
|
2023-07-17 01:00:16 +08:00
|
|
|
onRequest:
|
|
|
|
(RequestOptions options, RequestInterceptorHandler handler) async {
|
2023-07-04 11:51:11 +08:00
|
|
|
String baseUrl = options.baseUrl.replaceFirst('/api', '');
|
|
|
|
options.baseUrl = baseUrl;
|
2023-07-17 01:00:16 +08:00
|
|
|
if (getIt.get<Token>().token != '') {
|
|
|
|
options.headers['Authorization'] =
|
|
|
|
'Bearer ${getIt.get<Token>().token}';
|
|
|
|
}
|
2023-07-04 11:51:11 +08:00
|
|
|
return handler.next(options);
|
|
|
|
},
|
|
|
|
onResponse: (Response response, ResponseInterceptorHandler handler) {
|
|
|
|
if (response.statusCode! >= 200 && response.statusCode! < 400) {
|
2023-07-17 01:00:16 +08:00
|
|
|
if (response.headers.value('Authorization') != null) {
|
|
|
|
// update token
|
|
|
|
getIt
|
|
|
|
.get<Token>()
|
|
|
|
.updateToken(response.headers.value('Authorization')!);
|
|
|
|
}
|
2023-07-04 11:51:11 +08:00
|
|
|
return handler.resolve(response);
|
|
|
|
} else {
|
|
|
|
handler.reject(
|
|
|
|
DioException.badResponse(
|
|
|
|
statusCode: response.statusCode!,
|
|
|
|
requestOptions: RequestOptions(),
|
|
|
|
response: response,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
onError: (DioException e, ErrorInterceptorHandler handler) {
|
|
|
|
handler.reject(e);
|
|
|
|
},
|
|
|
|
),
|
|
|
|
);
|