-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
conversion_layer_adapter.dart
92 lines (82 loc) · 2.54 KB
/
conversion_layer_adapter.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:http/http.dart';
/// A conversion layer which translates Dio HTTP requests to
/// [http](https://pub.dev/packages/http) compatible requests.
/// This way there's no need to implement custom [HttpClientAdapter]
/// for each platform. Therefore, the required effort to add tests is kept
/// to a minimum. Since `CupertinoClient` and `CronetClient` depend anyway on
/// `http` this also doesn't add any additional dependency.
class ConversionLayerAdapter implements HttpClientAdapter {
ConversionLayerAdapter(this.client);
final Client client;
@override
Future<ResponseBody> fetch(
RequestOptions options,
Stream<Uint8List>? requestStream,
Future<dynamic>? cancelFuture,
) async {
final request = await _fromOptionsAndStream(options, requestStream);
final response = await client.send(request);
return response.toDioResponseBody(options);
}
@override
void close({bool force = false}) => client.close();
Future<BaseRequest> _fromOptionsAndStream(
RequestOptions options,
Stream<Uint8List>? requestStream,
) async {
final request = Request(
options.method,
options.uri,
);
request.headers.addAll(
Map.fromEntries(
options.headers.entries.map(
(e) => MapEntry(
options.preserveHeaderCase ? e.key : e.key.toLowerCase(),
e.value.toString(),
),
),
),
);
request.followRedirects = options.followRedirects;
request.maxRedirects = options.maxRedirects;
if (requestStream != null) {
final completer = Completer<Uint8List>();
final sink = ByteConversionSink.withCallback(
(bytes) => completer.complete(
bytes is Uint8List ? bytes : Uint8List.fromList(bytes),
),
);
requestStream.listen(
sink.add,
onError: completer.completeError,
onDone: sink.close,
cancelOnError: true,
);
final bytes = await completer.future;
request.bodyBytes = bytes;
}
return request;
}
}
extension on StreamedResponse {
ResponseBody toDioResponseBody(RequestOptions options) {
final dioHeaders = headers.entries.map(
(e) => MapEntry(
options.preserveHeaderCase ? e.key : e.key.toLowerCase(),
[e.value],
),
);
return ResponseBody(
stream.cast<Uint8List>(),
statusCode,
headers: Map.fromEntries(dioHeaders),
isRedirect: isRedirect,
statusMessage: reasonPhrase,
);
}
}