Client constructor

Client({
  1. required String baseURL,
  2. required String accessTokenKey,
  3. Map<String, dynamic>? headers,
  4. bool showLogging = true,
  5. Function? handleWhenUnauthorized,
  6. Duration? connectTimeout,
  7. Duration? receiveTimeout,
  8. List<int>? hitCacheOnErrorExcept,
  9. Duration? maxStaleCache,
  10. dynamic handleOnRequest(
    1. RequestOptions requestOptions
    )?,
  11. dynamic handleOnResponse(
    1. Response response
    )?,
  12. dynamic handleOnError(
    1. DioException err,
    2. ErrorInterceptorHandler handler
    )?,
  13. dynamic handleFilterLog(
    1. RequestOptions options,
    2. FilterArgs args
    )?,
  14. 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);
    },
  ));
}