Client constructor
Client({
- required String baseURL,
- required String accessTokenKey,
- Map<
String, dynamic> ? headers, - bool showLogging = true,
- Function? handleWhenUnauthorized,
- Duration? connectTimeout,
- Duration? receiveTimeout,
- List<
int> ? hitCacheOnErrorExcept, - Duration? maxStaleCache,
- dynamic handleOnRequest(
- RequestOptions requestOptions
- dynamic handleOnResponse(
- Response response
- dynamic handleOnError(
- DioException err,
- ErrorInterceptorHandler handler
- dynamic handleFilterLog(
- RequestOptions options,
- FilterArgs args
- bool useCache = false,
Implementation
Client(
{required this.baseURL,
required this.accessTokenKey,
this.headers,
this.showLogging = true,
this.handleWhenUnauthorized,
this.connectTimeout,
this.receiveTimeout,
this.hitCacheOnErrorExcept,
this.maxStaleCache,
this.handleOnRequest,
this.handleOnResponse,
this.handleOnError,
this.handleFilterLog,
this.useCache = false}) {
dio = Dio();
dio.options.baseUrl = baseURL;
dio.options.connectTimeout = connectTimeout ?? 120.seconds;
dio.options.receiveTimeout = receiveTimeout ?? 120.seconds;
if (useCache) {
if (!kIsWeb) {
dio.interceptors.add(cacheInterceptor(
maxStale: maxStaleCache, hitCacheOnErrorExcept: hitCacheOnErrorExcept));
}
}
if (showLogging) {
dio.interceptors.add(PrettyDioLogger(
requestHeader: true,
requestBody: true,
responseBody: true,
responseHeader: false,
error: true,
compact: true,
maxWidth: 90,
enabled: kDebugMode,
request: true,
filter: (options, args) {
if (handleFilterLog != null) {
handleFilterLog!(options, args);
}
// don't print responses with unit8 list data
return !args.isResponse || !args.hasUint8ListData;
}));
}
dio.interceptors.add(InterceptorsWrapper(
onRequest: (options, handler) async {
options.headers.addAll(headers ?? {});
// Tambahkan Authorization jika tidak ada custom header yang mengaturnya
if (!options.headers.containsKey('Authorization')) {
final token = await _getAccessToken();
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
}
handleOnRequest?.call(options);
handler.next(options);
},
onResponse: (response, handler) {
handleOnResponse?.call(response);
handler.next(response);
},
onError: (DioException error, handler) async {
log("Dio Error: ${error.message}", name: "OS_BASECODE");
if (error.response?.statusCode == 401) {
handleWhenUnauthorized?.call();
}
handleOnError?.call(error, handler);
handler.next(error);
},
));
}