Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hello Conversion Layer Adapter #1976

Merged
merged 23 commits into from
Jan 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/ISSUE_TEMPLATE/bug.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ body:
description: Which package has a problem?
options:
- dio
- compatibility_layer
- cookie_manager
- http2_adapter
- native_dio_adapter
Expand Down
1 change: 1 addition & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions README-ZH.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ Language: [English](README.md) | 简体中文

- cookie_manager: [链接](plugins/cookie_manager)
[![Pub](https://img.shields.io/pub/v/dio_cookie_manager.svg?label=dev&include_prereleases)](https://pub.flutter-io.cn/packages/dio_cookie_manager)
- compatibility_layer: [链接](plugins/compatibility_layer)
[![Pub](https://img.shields.io/pub/v/dio_compatibility_layer.svg?label=dev&include_prereleases)](https://pub.flutter-io.cn/packages/dio_compatibility_layer)
- http2_adapter: [链接](plugins/http2_adapter)
[![Pub](https://img.shields.io/pub/v/dio_http2_adapter.svg?label=dev&include_prereleases)](https://pub.flutter-io.cn/packages/dio_http2_adapter)
- native_dio_adapter: [链接](plugins/native_dio_adapter)
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ See the [Migration Guide][] for the complete breaking changes list.**

- cookie_manager: [link](plugins/cookie_manager)
[![Pub](https://img.shields.io/pub/v/dio_cookie_manager.svg?label=dev&include_prereleases)](https://pub.dev/packages/dio_cookie_manager)
- compatibility_layer: [link](plugins/compatibility_layer)
[![Pub](https://img.shields.io/pub/v/dio_compatibility_layer.svg?label=dev&include_prereleases)](https://pub.dev/packages/dio_compatibility_layer)
- http2_adapter: [link](plugins/http2_adapter)
[![Pub](https://img.shields.io/pub/v/dio_http2_adapter.svg?label=dev&include_prereleases)](https://pub.dev/packages/dio_http2_adapter)
- native_dio_adapter: [link](plugins/native_dio_adapter)
Expand Down
3 changes: 0 additions & 3 deletions dio_workspace.iml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/plugins/cookie_manager/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/plugins/cookie_manager/.pub" />
<excludeFolder url="file://$MODULE_DIR$/plugins/cookie_manager/build" />
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/build" />
Expand Down
7 changes: 7 additions & 0 deletions plugins/compatibility_layer/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/

# Avoid committing pubspec.lock for library packages; see
# https://dart.dev/guides/libraries/private-files#pubspeclock.
pubspec.lock
9 changes: 9 additions & 0 deletions plugins/compatibility_layer/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# CHANGELOG

## Unreleased

*None.*

## 0.1.0

- Initial version.
21 changes: 21 additions & 0 deletions plugins/compatibility_layer/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 The CFUG Team

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
47 changes: 47 additions & 0 deletions plugins/compatibility_layer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# dio_compatibility_layer

[![pub package](https://img.shields.io/pub/v/dio_compatibility_layer.svg)](https://pub.dev/packages/dio_compatibility_layer)
[![likes](https://img.shields.io/pub/likes/dio_compatibility_layer)](https://pub.dev/packages/dio_compatibility_layer/score)
[![popularity](https://img.shields.io/pub/popularity/dio_compatibility_layer)](https://pub.dev/packages/dio_compatibility_layer/score)
[![pub points](https://img.shields.io/pub/points/dio_compatibility_layer)](https://pub.dev/packages/dio_compatibility_layer/score)

If you encounter bugs, consider fixing it by opening a PR or at least contribute a failing test case.

This package contains adapters for [Dio](https://pub.dev/packages/dio)
which enables you to make use of other HTTP clients as the underlying implementation.

Currently, it supports compatibility with
- [`http`](https://pub.dev/packages/http)

## Get started

### Install

Add the `dio_compatibility_layer` package to your
[pubspec dependencies](https://pub.dev/packages/dio_compatibility_layer/install).

### Example

To use the `http` compatibility:

```dart
import 'package:dio/dio.dart';
import 'package:dio_compatibility_layer/dio_compatibility_layer.dart';
import 'package:http/http.dart';

void main() async {
// Start in the `http` world. You can use `http`, `cronet_http`,
// `cupertino_http` and other `http` compatible packages.
final httpClient = Client();

// Make the `httpClient` compatible via the `ConversionLayerAdapter` class.
final dioAdapter = ConversionLayerAdapter(httpClient);

// Make dio use the `httpClient` via the conversion layer.
final dio = Dio()..httpClientAdapter = dioAdapter;

// Make a request
final response = await dio.get('https://dart.dev');
print(response);
}
```
7 changes: 7 additions & 0 deletions plugins/compatibility_layer/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
include: ../../analysis_options.yaml

analyzer:
language:
strict-raw-types: true
strict-casts: true
strict-inference: true
12 changes: 12 additions & 0 deletions plugins/compatibility_layer/dart_test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
presets:
# empty placeholder required in CI scripts
all:

override_platforms:
chrome:
settings:
headless: true
firefox:
settings:
# headless argument has to be set explicitly for non-chrome browsers
arguments: --headless
16 changes: 16 additions & 0 deletions plugins/compatibility_layer/dio_compatibility_layer.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Dart SDK" level="project" />
<orderEntry type="library" name="Dart Packages" level="project" />
</component>
</module>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import 'package:dio/dio.dart';
import 'package:dio_compatibility_layer/dio_compatibility_layer.dart';
import 'package:http/http.dart';

void main() async {
// Start in the `http` world. You can use `http`, `cronet_http`,
// `cupertino_http` and other `http` compatible packages.
final httpClient = Client();

// Make the `httpClient` compatible via the `ConversionLayerAdapter` class.
final dioAdapter = ConversionLayerAdapter(httpClient);

// Make dio use the `httpClient` via the conversion layer.
final dio = Dio()..httpClientAdapter = dioAdapter;

// Make a request.
final response = await dio.get<dynamic>('https://dart.dev');
print(response);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
library dio_compatibility_layer;

export 'src/conversion_layer_adapter.dart';
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:http/http.dart' as http;

const _kIsWeb = bool.hasEnvironment('dart.library.js_util')
? bool.fromEnvironment('dart.library.js_util')
: identical(0, 0.0);

/// A conversion layer which translates [Dio] requests to
/// [`http`](https://pub.dev/packages/http) compatible requests.
/// This enables you to use
/// [`cronet_http`](https://pub.dev/packages/cronet_http),
/// [`cupertino_http`](https://pub.dev/packages/cupertino_http),
/// and other `http` compatible packages with [Dio].
class ConversionLayerAdapter implements HttpClientAdapter {
ConversionLayerAdapter(this.client);

/// The client instance from the `http` package.
final http.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 ResponseBody(
response.stream.cast<Uint8List>(),
response.statusCode,
statusMessage: response.reasonPhrase,
isRedirect: response.isRedirect,
headers: Map.fromEntries(
response.headers.entries.map((e) => MapEntry(e.key, [e.value])),
),
);
}

@override
void close({bool force = false}) => client.close();

Future<http.BaseRequest> _fromOptionsAndStream(
RequestOptions options,
Stream<Uint8List>? requestStream,
) async {
final http.BaseRequest request;
if (_kIsWeb && requestStream != null) {
final normalRequest = request = http.Request(
options.method,
options.uri,
);
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;
normalRequest.bodyBytes = bytes;
} else if (requestStream != null) {
final streamedRequest = request = http.StreamedRequest(
options.method,
options.uri,
);
requestStream.listen(
streamedRequest.sink.add,
onError: streamedRequest.sink.addError,
onDone: streamedRequest.sink.close,
cancelOnError: true,
);
} else {
request = http.Request(options.method, options.uri);
}
request.headers.addAll(
Map.fromEntries(
options.headers.entries.map(
(e) => MapEntry(e.key, e.value.toString().trim()),
),
),
);
request
..followRedirects = options.followRedirects
..maxRedirects = options.maxRedirects
..persistentConnection = options.persistentConnection;
return request;
}
}
24 changes: 24 additions & 0 deletions plugins/compatibility_layer/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: dio_compatibility_layer
version: 0.1.0

description: Enables dio to make use of http packages.
topics:
- dio
- http
- network
- native
- cronet
homepage: https://github.com/cfug/dio
repository: https://github.com/cfug/dio/blob/main/plugins/compatibility_layer
issue_tracker: https://github.com/cfug/dio/issues

environment:
sdk: ^3.0.0

dependencies:
dio: ^5.2.0
http: ^1.0.0

dev_dependencies:
lints: any
test: any
27 changes: 27 additions & 0 deletions plugins/compatibility_layer/test/client_mock.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import 'package:http/http.dart';

class CloseClientMock implements Client {
bool closeWasCalled = false;

@override
void close() {
closeWasCalled = true;
}

@override
dynamic noSuchMethod(Invocation i) => super.noSuchMethod(i);
}

class ClientMock implements Client {
StreamedResponse? response;
BaseRequest? request;

@override
Future<StreamedResponse> send(BaseRequest request) async {
this.request = request;
return response!;
}

@override
dynamic noSuchMethod(Invocation i) => super.noSuchMethod(i);
}
Loading