Comments (3)
extra
does not involved with any computation of the request. Could you attach a minimal reproducible example?
from dio.
/*
* Copyright © 2023, This code is developed by
* Under work enviorment of tata money.Sharing and distributor source code outside organisaton is prohibited.
*/
import 'dart:io';
import 'package:colorize/colorize.dart';
import 'package:dio/dio.dart' as d;
import 'package:dio/dio.dart';
import 'package:dio_smart_retry/dio_smart_retry.dart';
import 'package:file_support/file_support.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import 'package:tata_impact_new/data/datasources/local/services/file_service.dart';
import 'package:tata_impact_new/data/datasources/network/modules/enviorment_module.dart';
import 'package:tata_impact_new/data/datasources/network/modules/user_experia_dio_interceptor.dart';
import 'package:tata_impact_new/data/datasources/network/services/user_experior_service.dart';
import 'package:tata_impact_new/data/datasources/network/utils/dio_performance_adapter.dart';
import 'package:tata_impact_new/data/datasources/network/utils/handle_response.dart';
import 'package:tata_impact_new/data/models/user_experia_model.dart';
import 'package:tata_impact_new/data/repositories/core/i_core_data_repo.dart';
import 'package:tata_impact_new/data/repositories/firebase_analytics_events/i_firebase_analytics_event.dart';
import 'package:tata_impact_new/dependency_injection/inject.dart';
import 'package:tata_impact_new/utils/utils.dart';
import 'package:uuid/uuid.dart';
import '../../../../utils/FLocation.dart';
import '../../local/services/kv_storage_service.dart';
import 'package:uuid/uuid.dart' as uuid;
/*---------------------------------Interceptors ---------------------------*/
class MasterInterceptor extends d.Interceptor {
final showToken = true;
@override
void onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
MEnviorment enviorment = getIt<MEnviorment>();
String? _token = await getIt<KVStorageService>().accessToken;
String? _rToken = await getIt<KVStorageService>().refreshToken;
options.connectTimeout = const Duration(seconds: 30);
if (_token != null || _rToken != null) {
_token!.printinfo;
_rToken!.printinfo;
}
if (showToken && (enviorment.env == ENVIORMENT.debug)) {
color("TOKEN: ${_token}\n",
front: Styles.BG_GREEN,
isBold: true,
isItalic: false,
isUnderline: false);
color("R-TOKEN: ${_rToken}\n",
front: Styles.BG_BLUE,
isBold: true,
isItalic: false,
isUnderline: false);
}
/* String lat = kReleaseMode
? Flocation.instance.locationData?.latitude.toString() ?? ""
: "25.98217";
String long = kReleaseMode
? Flocation.instance.locationData?.longitude.toString() ?? ""
: "80.10131";*/
String lat = Flocation.instance.locationData?.latitude.toString() ?? "";
String long = Flocation.instance.locationData?.longitude.toString() ?? "";
//package
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String _version = packageInfo.version;
// clientId
String role = "";
try {
role = getIt<ICoreDataRepo>().coreData.role;
} catch (e) {
role = "";
}
options.headers.addAll({
'clientId': getIt<ICoreDataRepo>().clientId ?? "",
'latitude': lat ?? "",
'Longitude': long ?? "",
'token': _token ?? "",
'r-token': _rToken ?? "",
'appVer': _version,
'userRole': role,
'lang': "en",
'merchant': "IMPACT",
});
print("sending data ${options.headers.toString()}");
return super.onRequest(options, handler); // its required to add
}
@override
void onError(d.DioException err, ErrorInterceptorHandler handler) {
if (err.response!.statusCode == 403) {
print("seassion expire");
} else if (err.response!.statusCode == 400) {
getIt<IFireBaseAnalyticsEventRepo>().apiRecord400Error(
(err.response?.requestOptions.baseUrl ?? "") +
(err.response?.requestOptions.path ?? ""));
}
return handler.next(err);
}
@override
void onResponse(
d.Response response, ResponseInterceptorHandler handler) async {
if (response.statusCode == 400) {
getIt<IFireBaseAnalyticsEventRepo>().apiRecord400Error(
(response.requestOptions.baseUrl ?? "") +
(response.requestOptions.path ?? ""));
}
return super.onResponse(response, handler);
}
}
class AuthenticationInterceptor extends d.Interceptor {
final showToken = true;
// this is not staging ot prod url its other Url that is using for authentication
static const LOGIN_API_ENDPOINT =
"https://dl.tatamoney.com/auth/gouth/impact/app";
static const LOGIN_WITH_EMAIL_API_ENDPOINT =
"https://dl.tatamoney.com/auth/loginStore/impact/app";
static const LOGIN_WITH_STAGING_API_ENDPOINT =
"https://stgapp.tatamoney.com/impact-auth/gouth/impact/app";
@override
void onResponse(
d.Response response, ResponseInterceptorHandler handler) async {
if (((response.requestOptions.baseUrl + response.requestOptions.path)
.contains(LOGIN_API_ENDPOINT) ||
(response.requestOptions.baseUrl + response.requestOptions.path)
.contains(LOGIN_WITH_EMAIL_API_ENDPOINT)) ||
(response.requestOptions.baseUrl + response.requestOptions.path)
.contains(LOGIN_WITH_STAGING_API_ENDPOINT) &&
response.statusCode == 200) {
String _token = response.headers["token"]?.first ?? "null";
String _rToken = response.headers["r-token"]?.first ?? "null";
await getIt<KVStorageService>().setAccessToken(_token);
await getIt<KVStorageService>().setRefreshToken(_rToken);
//await getIt<AuthInterceptor>().initialize();
}
return super.onResponse(response, handler);
}
}
/*Client logic*/
class DioClient with HandleApiResultMixin {
late KVStorageService _kvStorageService;
d.Dio? dio;
String baseUrl;
String stagingUrl;
DioClient({required this.baseUrl, required this.stagingUrl}) {
_initalised();
}
_initalised() async {
MEnviorment menviorment = getIt<MEnviorment>();
if (menviorment.env == ENVIORMENT.prod) {
baseUrl = baseUrl;
} else {
baseUrl = stagingUrl;
}
dio = d.Dio();
dio!.options.baseUrl = baseUrl;
dio!.interceptors.addAll(
[
/* RetryInterceptor(
dio: dio!,
logPrint: print, // specify log function (optional)
retries: 3, // retry count (optional)
retryDelays: const [
Duration(seconds: 5),
Duration(seconds: 10),
Duration(seconds: 30),
],
),*/
UserExperiaDioInterceptor(),
AuthenticationInterceptor(),
MasterInterceptor(),
DioFirebasePerformanceInterceptor(),
PrettyDioLogger(
requestHeader: true,
requestBody: true,
error: true,
responseBody: true,
responseHeader: false,
compact: false,
),
],
);
}
Future<d.Response> get(String path, Map<String, dynamic> queryparms,
{d.CancelToken? cancelToken,UserExperiaModel? userExperiaModel}) async {
if (dio == null) {
await _initalised();
}
d.Response response = await dio!
.get(path, queryParameters: queryparms, cancelToken: cancelToken);
return response;
}
@AlexV525 pls focus this i am adding here extras.
Future<d.Response> post(String path, Map<String, dynamic> data,
{String? baseUrl = null, d.CancelToken? cancelToken,UserExperiaModel? userExperiaModel}) async {
if (dio == null) {
await _initalised();
}
if(userExperiaModel!=null){
userExperiaModel=userExperiaModel.copyWith(properties: userExperiaModel.properties.copyWith(requestBody: data.toString()));
dio!.options.copyWith(extra: userExperiaModel.toJson());
}
dio!.options.contentType = "application/json";
d.Response response =
await dio!.post(path , data: data, cancelToken: cancelToken);
return response;
}
Future<d.Response> postWithQueryParameters(
String path, Map<String, dynamic> data,
{Map<String, dynamic>? queryParams}) async {
if (dio == null) {
await _initalised();
}
dio!.options.contentType = "application/json";
d.Response response =
await dio!.post(path, queryParameters: queryParams, data: data);
return response;
}
Future<d.Response> postFormDataWithQueryParameters(
String path, Map<String, dynamic> data,
{Map<String, dynamic>? queryParams}) async {
dio!.options.contentType = "multipart/form-data";
if (dio == null) {
await _initalised();
}
return await dio!.post(path,
queryParameters: queryParams, data: d.FormData.fromMap(data));
}
//post raw data
Future<d.Response> postRawDataWithQueryParameters(String path,
{required Map<String, dynamic> queryParams,
required Map<String, dynamic> data}) async {
if (dio == null) {
await _initalised();
}
return await dio!.post(path, queryParameters: queryParams, data: data);
}
// post form data
Future<d.Response> postFormData(
String path, Map<String, dynamic> data) async {
dio!.options.contentType = "multipart/form-data";
if (dio == null) {
await _initalised();
}
return await dio!.post(
path,
data: d.FormData.fromMap(data),
);
}
/// used to take compress image form multipart
Future<d.MultipartFile> getMultiPartImage(File file) async {
"FILE PATH: ${file.path}".printinfo;
File? compressFile = await FileSupport().compressImage(file, quality: 50);
final d.MultipartFile multipart = await d.MultipartFile.fromFile(file.path);
return multipart;
}
Future<d.MultipartFile> getMultiPartImageCompressed(File file) async {
"FILE PATH: ${file.path}".printinfo;
File? compressFile = await getIt<FileService>().getCompressImage(file);
d.MultipartFile multipart =
await d.MultipartFile.fromFile(compressFile.path);
return multipart;
}
Future<d.MultipartFile> getMultiPart(File file) async {
"FILE PATH: ${file.path}".printinfo;
d.MultipartFile multipart = await d.MultipartFile.fromFile(file.path);
return multipart;
}
Future<DioClient> init() async {
await _initalised();
return this;
}
}
from dio.
Your code involves too many unrelated implementations and they are also inaccessible to us. Please make a minimal example to reproduce your case.
from dio.
Related Issues (20)
- Dio (HttpClient) cannot set a self-signed trust certificate HOT 4
- [Proposal] Improve toString() of InterceptorState
- Cronet exception: m.ms: Exception in CronetUrlRequest: net::ERR_CONNECTION_CLOSED, ErrorCode=5 HOT 2
- 503 Status Code With the Https base URL HOT 1
- Type Casting Error: '_Map<String, dynamic>' is not a Subtype of 'T?' HOT 1
- Issue with API call when android device is connected via wifi. HOT 1
- Uploading with FormData throws a TypeError: type 'List<int>' is not a subtype of type 'Uint8List' of 'value' HOT 6
- Opportunity to improve the json decoding performance HOT 3
- FormData and List of Int not working as expected. HOT 2
- flutter dynamic coockies management HOT 1
- post请求超时无反应 HOT 1
- Error Dio flutter web HOT 1
- upload file send timeout
- Header is out of order HOT 3
- `ResponseType.stream` is not working on web. HOT 1
- [🔔 Dio] sendTimeout cannot be used without a request body to send HOT 2
- `Transformer.isJsonMimeType` throws format exceptions without caught
- onError is not returning any error HOT 3
- Error when uploading image using MultipartFile.fromBytes in version 5.4.3+1 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from dio.