Skip to content
This repository has been archived by the owner on Feb 13, 2023. It is now read-only.

Commit

Permalink
Clean code (#34)
Browse files Browse the repository at this point in the history
* 🚨 Fix linter rules

* ⚡️ Add missing type infer

* 🚀 Move around `download` and `downloadUri`

* ⚡️ Improve fields' definition with multiple classes

* ⚡️ Improve docs and comments

* ⚡️ Improve interceptor's internal classes

* 🎨 Reorg tests

* 🎨 ++

* 📝 Fix broken links

* 🎨 `Object` -> `dynamic` in `download()`

* 🥅 Improve type checks
  • Loading branch information
AlexV525 authored Dec 16, 2022
1 parent 20a5920 commit acbf115
Show file tree
Hide file tree
Showing 27 changed files with 348 additions and 513 deletions.
4 changes: 2 additions & 2 deletions dio/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ the subsequent interceptors processing logic more finely (whether to skip them o
### New features

- Support Flutter Web.
- Extract [CookieManager](/plugins/cookie_manager) into a separate package(No need for Flutter Web).
- Provides [HTTP/2.0 HttpClientAdapter](/plugins/http2_adapter).
- Extract [CookieManager](../plugins/cookie_manager) into a separate package(No need for Flutter Web).
- Provides [HTTP/2.0 HttpClientAdapter](../plugins/http2_adapter).

### Change List

Expand Down
9 changes: 5 additions & 4 deletions dio/analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ analyzer:
errors:
deprecated_member_use_from_same_package: ignore
todo: ignore

linter:
rules:
- prefer_final_fields: true
- prefer_final_locals: true
- prefer_final_in_for_each: true
- unnecessary_parenthesis: true
- prefer_final_fields
- prefer_final_locals
- prefer_final_in_for_each
- unnecessary_parenthesis
8 changes: 4 additions & 4 deletions dio/lib/src/adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ class ResponseBody {
this.redirects,
});

/// The response stream
/// The response stream.
Stream<Uint8List> stream;

/// the response headers
late Map<String, List<String>> headers;
/// The response headers.
Map<String, List<String>> headers;

/// Http status code
/// HTTP status code.
int statusCode;

/// Returns the reason phrase associated with the status code.
Expand Down
13 changes: 4 additions & 9 deletions dio/lib/src/adapters/browser_adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import '../options.dart';

HttpClientAdapter createAdapter() => BrowserHttpClientAdapter();

/// The default [HttpClientAdapter] for Web platforms.
class BrowserHttpClientAdapter implements HttpClientAdapter {
/// These are aborted if the client is closed.
final _xhrs = <HttpRequest>{};
Expand Down Expand Up @@ -55,7 +56,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
final completer = Completer<ResponseBody>();

xhr.onLoad.first.then((_) {
Uint8List body = (xhr.response as ByteBuffer).asUint8List();
final Uint8List body = (xhr.response as ByteBuffer).asUint8List();
completer.complete(
ResponseBody.fromBytes(
body,
Expand Down Expand Up @@ -117,10 +118,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
if (duration > sendTimeout) {
uploadStopwatch.stop();
completer.completeError(
DioError.sendTimeout(
timeout: sendTimeout,
requestOptions: options,
),
DioError.sendTimeout(timeout: sendTimeout, requestOptions: options),
StackTrace.current,
);
xhr.abort();
Expand Down Expand Up @@ -186,10 +184,7 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
connectTimeoutTimer?.cancel();
try {
xhr.abort();
} catch (e) {
// ignore
}

} catch (_) {}
// xhr.onError will not triggered when xhr.abort() called.
// so need to manual throw the cancel error to avoid Future hang ups.
// or added xhr.onAbort like axios did https://github.com/axios/axios/blob/master/lib/adapters/xhr.js#L102-L111
Expand Down
34 changes: 20 additions & 14 deletions dio/lib/src/adapters/io_adapter.dart
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import '../adapter.dart';
import '../options.dart';
import '../dio_error.dart';
import '../options.dart';
import '../redirect_record.dart';

@Deprecated('Use IOHttpClientAdapter instead. This will be removed in 6.0.0')
typedef DefaultHttpClientAdapter = IOHttpClientAdapter;

typedef OnHttpClientCreate = HttpClient? Function(HttpClient client);
typedef ValidateCertificate = bool Function(
X509Certificate? certificate, String host, int port);
X509Certificate? certificate,
String host,
int port,
);

HttpClientAdapter createAdapter() => IOHttpClientAdapter();

/// The default HttpClientAdapter for Dio.
/// The default [HttpClientAdapter] for native platforms.
class IOHttpClientAdapter implements HttpClientAdapter {
/// [Dio] will create HttpClient when it is needed.
/// If [onHttpClientCreate] is provided, [Dio] will call
Expand All @@ -41,8 +45,9 @@ class IOHttpClientAdapter implements HttpClientAdapter {
Future<void>? cancelFuture,
) async {
if (_closed) {
throw Exception(
"Can't establish connection after [HttpClientAdapter] closed!");
throw StateError(
"Can't establish connection after the adapter was closed!",
);
}
final httpClient = _configHttpClient(cancelFuture, options.connectTimeout);
final reqFuture = httpClient.openUrl(options.method, options.uri);
Expand All @@ -64,7 +69,7 @@ class IOHttpClientAdapter implements HttpClientAdapter {
request = await reqFuture;
}

//Set Headers
// Set Headers
options.headers.forEach((k, v) {
if (v != null) request.headers.set(k, v);
});
Expand Down Expand Up @@ -102,7 +107,6 @@ class IOHttpClientAdapter implements HttpClientAdapter {
},
);
}

await future;
}

Expand All @@ -126,8 +130,11 @@ class IOHttpClientAdapter implements HttpClientAdapter {
if (validateCertificate != null) {
final host = options.uri.host;
final port = options.uri.port;
final isCertApproved =
validateCertificate!(responseStream.certificate, host, port);
final bool isCertApproved = validateCertificate!(
responseStream.certificate,
host,
port,
);
if (!isCertApproved) {
throw DioError(
requestOptions: options,
Expand All @@ -138,9 +145,8 @@ class IOHttpClientAdapter implements HttpClientAdapter {
}
}

final stream =
responseStream.transform<Uint8List>(StreamTransformer.fromHandlers(
handleData: (data, sink) {
final stream = responseStream.transform<Uint8List>(
StreamTransformer.fromHandlers(handleData: (data, sink) {
stopwatch.stop();
final duration = stopwatch.elapsed;
final receiveTimeout = options.receiveTimeout;
Expand All @@ -155,8 +161,8 @@ class IOHttpClientAdapter implements HttpClientAdapter {
} else {
sink.add(Uint8List.fromList(data));
}
},
));
}),
);

final headers = <String, List<String>>{};
responseStream.headers.forEach((key, values) {
Expand Down
34 changes: 15 additions & 19 deletions dio/lib/src/cancel_token.dart
Original file line number Diff line number Diff line change
@@ -1,45 +1,41 @@
import 'dart:async';

import 'dio_error.dart';
import 'options.dart';

/// You can cancel a request by using a cancel token.
/// An instance which controls cancellation of [Dio]'s requests,
/// build from [Completer].
///
/// You can cancel requests by using a [CancelToken].
/// One token can be shared with different requests.
/// when a token's [cancel] method invoked, all requests
/// with this token will be cancelled.
/// When [cancel] is invoked, all requests using this token will be cancelled.
class CancelToken {
CancelToken() {
_completer = Completer<DioError>();
}
CancelToken();

/// Whether is throw by [cancel]
static bool isCancel(DioError e) {
return e.type == DioErrorType.cancel;
}
final Completer<DioError> _completer = Completer<DioError>();

/// If request have been canceled, save the cancel Error.
DioError? _cancelError;
/// Whether the [error] is thrown by [cancel].
static bool isCancel(DioError error) => error.type == DioErrorType.cancel;

/// If request have been canceled, save the cancel Error.
/// If request have been canceled, save the cancel error.
DioError? get cancelError => _cancelError;

late Completer<DioError> _completer;
DioError? _cancelError;

RequestOptions? requestOptions;

/// whether cancelled
/// Whether the token is cancelled.
bool get isCancelled => _cancelError != null;

/// When cancelled, this future will be resolved.
Future<DioError> get whenCancel => _completer.future;

/// Cancel the request
/// Cancel the request with the given [reason].
void cancel([Object? reason]) {
_cancelError = DioError.requestCancelled(
requestOptions: requestOptions ?? RequestOptions(path: ''),
requestOptions: requestOptions ?? RequestOptions(),
reason: reason,
stackTrace: StackTrace.current,
);

if (!_completer.isCompleted) {
_completer.complete(_cancelError);
}
Expand Down
Loading

0 comments on commit acbf115

Please sign in to comment.