Skip to content

Commit

Permalink
[dio] 💡 Improve comments (#1772)
Browse files Browse the repository at this point in the history
- [x] adapters
- [x] dio
- [x] transformers
- [x] cancel token
- [x] dio error
- [x] dio mixin
- [x] form data
- [x] headers
- [x] multipart file
- [x] interceptors
- [x] options
- [x] parameters
- [x] response
- [x] redirect record

---------

Signed-off-by: Alex Li <[email protected]>
  • Loading branch information
AlexV525 authored Jul 23, 2023
1 parent ef1ed39 commit 04ca761
Show file tree
Hide file tree
Showing 28 changed files with 798 additions and 830 deletions.
1 change: 1 addition & 0 deletions dio/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ See the [Migration Guide][] for the complete breaking changes list.**
- Remove `http` from `dev_dependencies`.
- Add support for cloning `MultipartFile` from `FormData`.
- Only produce null response body when `ResponseType.json`.
- Improve comments.

## 5.2.1+1

Expand Down
2 changes: 2 additions & 0 deletions dio/README-ZH.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,8 @@ print(response.requestOptions);
print(response.statusCode);
```

注意,`Response.extra``RequestOptions.extra` 是不同的实例,互相之间无关。

### 拦截器

每个 Dio 实例都可以添加任意多个拦截器,他们会组成一个队列,拦截器队列的执行顺序是先进先出。
Expand Down
9 changes: 6 additions & 3 deletions dio/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,8 +345,8 @@ ResponseType? responseType;
/// the request will be perceived as successful; otherwise, considered as failed.
ValidateStatus? validateStatus;
/// Custom field that you can retrieve it later in
/// [Interceptor], [Transformer] and the [Response] object.
/// Custom field that you can retrieve it later in [Interceptor],
/// [Transformer] and the [Response.requestOptions] object.
Map<String, dynamic>? extra;
/// Common query parameters.
Expand Down Expand Up @@ -391,7 +391,7 @@ bool isRedirect;
/// implementation of the adapter supports it or not.
List<RedirectRecord> redirects;
/// Custom fields that are constructed in the [RequestOptions].
/// Custom fields that only for the [Response].
Map<String, dynamic> extra;
/// Response headers.
Expand All @@ -408,6 +408,9 @@ print(response.requestOptions);
print(response.statusCode);
```

Be aware, the `Response.extra` is different from `RequestOptions.extra`,
they are not related to each other.

### Interceptors

For each dio instance, we can add one or more interceptors,
Expand Down
6 changes: 3 additions & 3 deletions dio/lib/dio.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// A powerful Http client for Dart, which supports Interceptors,
/// Global configuration, FormData, File downloading etc. and Dio is
/// very easy to use.
/// A powerful HTTP client for Dart and Flutter, which supports global settings,
/// [Interceptors], [FormData], aborting and canceling a request,
/// files uploading and downloading, requests timeout, custom adapters, etc.
library dio;

export 'src/adapter.dart';
Expand Down
87 changes: 45 additions & 42 deletions dio/lib/src/adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,84 +19,87 @@ import 'adapters/io_adapter.dart'
/// If you want to customize the [HttpClientAdapter] you should instead use
/// either [IOHttpClientAdapter] on `dart:io` platforms
/// or [BrowserHttpClientAdapter] on `dart:html` platforms.
///
/// ```dart
/// dio.httpClientAdapter = HttpClientAdapter();
/// ```
abstract class HttpClientAdapter {
/// Create a [HttpClientAdapter] based on the current platform (IO/Web).
factory HttpClientAdapter() => adapter.createAdapter();

/// We should implement this method to make real http requests.
/// Implement this method to make real HTTP requests.
///
/// [options] are the request options.
///
/// [requestStream] The request stream, It will not be null
/// only when http method is one of "POST","PUT","PATCH"
/// and the request body is not empty.
///
/// We should give priority to using requestStream(not options.data) as request data.
/// because supporting stream ensures the `onSendProgress` works.
/// [requestStream] is the request stream. It will not be null only when
/// the request body is not empty.
/// Use [requestStream] if your code rely on [RequestOptions.onSendProgress].
///
/// When cancelled the request, [cancelFuture] will be resolved!
/// you can listen cancel event by it, for example:
/// [cancelFuture] will be null when the [CancelToken]
/// is not set [CancelToken] for the request.
///
/// When the request is cancelled, [cancelFuture] will be resolved.
/// The adapter can listen cancel event like:
/// ```dart
/// cancelFuture?.then((_)=>print("request cancelled!"))
/// cancelFuture?.then((_)=>print("request cancelled!"))
/// ```
/// [cancelFuture] will be null when the request is not set [CancelToken].
Future<ResponseBody> fetch(
RequestOptions options,
Stream<Uint8List>? requestStream,
Future<void>? cancelFuture,
);

/// Close the current adapter and its inner clients or requests.
void close({bool force = false});
}

/// The response wrapper class for adapters.
///
/// This class should not be used in regular usages.
class ResponseBody {
ResponseBody(
this.stream,
this.statusCode, {
this.headers = const {},
this.statusMessage,
this.isRedirect = false,
this.redirects,
});

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

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

/// HTTP status code.
int statusCode;

/// Returns the reason phrase associated with the status code.
/// The reason phrase must be set before the body is written
/// to. Setting the reason phrase after writing to the body.
String? statusMessage;

/// Whether this response is a redirect.
final bool isRedirect;

List<RedirectRecord>? redirects;

Map<String, dynamic> extra = {};
Map<String, List<String>>? headers,
}) : headers = headers ?? {};

ResponseBody.fromString(
String text,
this.statusCode, {
this.headers = const {},
this.statusMessage,
this.isRedirect = false,
}) : stream = Stream.value(Uint8List.fromList(utf8.encode(text)));
Map<String, List<String>>? headers,
}) : stream = Stream.value(Uint8List.fromList(utf8.encode(text))),
headers = headers ?? {};

ResponseBody.fromBytes(
List<int> bytes,
this.statusCode, {
this.headers = const {},
this.statusMessage,
this.isRedirect = false,
}) : stream = Stream.value(Uint8List.fromList(bytes));
Map<String, List<String>>? headers,
}) : stream = Stream.value(Uint8List.fromList(bytes)),
headers = headers ?? {};

/// Whether this response is a redirect.
final bool isRedirect;

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

/// HTTP status code.
int statusCode;

/// Returns the reason phrase corresponds to the status code.
/// The message can be [HttpRequest.statusText]
/// or [HttpClientResponse.reasonPhrase].
String? statusMessage;

/// Stores redirections during the request.
List<RedirectRecord>? redirects;

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

/// The extra field which will pass-through to the [Response.extra].
Map<String, dynamic> extra = {};
}
7 changes: 3 additions & 4 deletions dio/lib/src/adapters/browser_adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'dart:html';
import 'dart:typed_data';

import 'package:meta/meta.dart';

import '../adapter.dart';
import '../dio_exception.dart';
import '../headers.dart';
Expand All @@ -24,7 +25,8 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
///
/// Defaults to `false`.
///
/// You can also override this value in Options.extra['withCredentials'] for each request
/// You can also override this value using `Options.extra['withCredentials']`
/// for each request.
bool withCredentials;

@override
Expand Down Expand Up @@ -201,9 +203,6 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
try {
xhr.abort();
} 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
if (!completer.isCompleted) {
completer.completeError(
DioException.requestCancelled(
Expand Down
7 changes: 5 additions & 2 deletions dio/lib/src/adapters/io_adapter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,22 @@ import '../redirect_record.dart';
@Deprecated('Use IOHttpClientAdapter instead. This will be removed in 6.0.0')
typedef DefaultHttpClientAdapter = IOHttpClientAdapter;

/// The signature of [IOHttpClientAdapter.onHttpClientCreate].
@Deprecated('Use CreateHttpClient instead. This will be removed in 6.0.0')
typedef OnHttpClientCreate = HttpClient? Function(HttpClient client);

/// The signature of [IOHttpClientAdapter.createHttpClient].
/// Can be used to provide a custom [HttpClient] for Dio.
typedef CreateHttpClient = HttpClient Function();

/// The signature of [IOHttpClientAdapter.validateCertificate].
typedef ValidateCertificate = bool Function(
X509Certificate? certificate,
String host,
int port,
);

/// Creates an [IOHttpClientAdapter].
HttpClientAdapter createAdapter() => IOHttpClientAdapter();

/// The default [HttpClientAdapter] for native platforms.
Expand Down Expand Up @@ -53,7 +57,6 @@ class IOHttpClientAdapter implements HttpClientAdapter {
ValidateCertificate? validateCertificate;

HttpClient? _cachedHttpClient;

bool _closed = false;

@override
Expand All @@ -64,7 +67,7 @@ class IOHttpClientAdapter implements HttpClientAdapter {
) async {
if (_closed) {
throw StateError(
"Can't establish connection after the adapter was closed!",
"Can't establish connection after the adapter was closed.",
);
}
final operation = CancelableOperation.fromFuture(_fetch(
Expand Down
13 changes: 8 additions & 5 deletions dio/lib/src/cancel_token.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import 'dart:async';
import 'dio_exception.dart';
import 'options.dart';

/// An instance which controls cancellation of [Dio]'s requests,
/// build from [Completer].
/// {@template dio.CancelToken}
/// Controls cancellation of [Dio]'s requests.
///
/// You can cancel requests by using a [CancelToken].
/// One token can be shared with different requests.
/// When [cancel] is invoked, all requests using this token will be cancelled.
/// The same token can be shared between different requests.
/// When [cancel] is invoked, requests bound to this token will be cancelled.
/// {@endtemplate}
class CancelToken {
CancelToken();

Expand All @@ -22,6 +22,9 @@ class CancelToken {
DioException? get cancelError => _cancelError;
DioException? _cancelError;

/// Corresponding request options for the request.
///
/// This field can be null if the request was never submitted.
RequestOptions? requestOptions;

/// Whether the token is cancelled.
Expand Down
Loading

0 comments on commit 04ca761

Please sign in to comment.