okdio 0.0.2

Build Status Coverage Status

Chopper is an http client generator using source_gen and inspired by Retrofit.

Usage #

Generator #

Add the generator to your dev dependencies

dependencies:
  chopper: ^2.0.0

dev_dependencies:
  build_runner: ^1.0.0
  chopper_generator: ^2.0.0

Define and Generate your API #

// my_service.dart

import "dart:async";
import 'package:chopper/chopper.dart';

part "my_service.chopper.dart";

@ChopperApi(baseUrl: "/resources")
abstract class MyService extends ChopperService {
  static MyService create([ChopperClient client]) => _$MyService(client);

  @Get(url: "{id}")
  Future<Response> getResource(@Path() String id);

  @Get(headers: const {"foo": "bar"})
  Future<Response<Map>> getMapResource(@Query() String id);

  @Post(url: 'multi')
  @multipart
  Future<Response> postResources(
    @Part('1') Map a,
    @Part('2') Map b,
    @Part('3') String c,
  );

  @Post(url: 'file')
  @multipart
  Future<Response> postFile(
    @FileField('file') List<int> bytes,
  );
}

then run the generator

pub run build_runner build

#flutter
flutter packages pub run build_runner build

Use it #

final chopper = ChopperClient(
    baseUrl: "http://localhost:8000",
    services: [
      // the generated service
      MyService.create()
    ],
    converter: JsonConverter(),
  );

final myService = MyService.create(chopper);

final response = await myService.getMapResource("1");

chopper.close();

Or create a Chopper client and inject your generated api.

import 'package:chopper/chopper.dart';

final chopper = new ChopperClient(
    baseUrl: "http://localhost:8000",
    services: [
      // the generated service
      MyService.create()
    ],
    converter: JsonConverter(),
);

final myService = chopper.service<MyService>(MyService);

Interceptors #

Request #

implement RequestInterceptor class or define function with following signature FutureOr<Request> RequestInterceptorFunc(Request request)

Request interceptor are called just before sending request

final chopper = new ChopperClient(
   interceptors: [
     (request) async => request.replace(body: {}),
   ]
);

Response #

implement ResponseInterceptor class or define function with following signature FutureOr<Response> ResponseInterceptorFunc(Response response)

Called after successfull or failed request

final chopper = new ChopperClient(
   interceptors: [
     (response) async => response.replace(body: {}),
   ]
);

Converter #

Converter is used to transform body, for example transforming a Dart object to a Map<String, dynamic>

Both converter and errorConverter are called before request and response intercptors.

errorConverter is called only on error response (statusCode < 200 || statusCode >= 300)

final chopper = new ChopperClient(
   converter: MyConverter(),
   errorConverter: MyErrorConverter()
);

More example #

Issue Tracker #

Changelog #

0.0.1 #

  • Initial version, created by Stagehand

example/main.dart

import 'dart:convert';
import 'dart:io';

import 'package:okdio/okdio.dart';
import 'package:okdio/src/interceptor.dart';
import 'definition.dart';
import 'package:rxdart/rxdart.dart';
import 'package:dio/dio.dart';
import 'json/person.dart';

main() async {
  print(1);
  init();
  print(2);
  const bool inProduction = const bool.fromEnvironment("dart.vm.product"); //release == true
  print(inProduction);
  final chopper = ChopperClient(
      baseUrl: "http://mockserver",
      services: [
        // the generated service
        MyService.create()
      ],
      onSendProgress: (int sent, int total) {
        print("$sent, $total");
      },
      adapter: MockAdapter(),
      errorConverter: (DioError error) {
        print("Error Happend: type:${error.type}, status[${error.response?.statusCode}]");
        switch(error.type) {
          case DioErrorType.DEFAULT:
            error.message = "网络出错啦";
            break;
          case DioErrorType.CANCEL:
            error.message = "";
            break;
          case DioErrorType.CONNECT_TIMEOUT:
            error.message = "连接超时";
            break;
          case DioErrorType.RECEIVE_TIMEOUT:
            error.message = "网络超时";
            break;
          case DioErrorType.SEND_TIMEOUT:
            error.message = "网络超时";
            break;
          case DioErrorType.RESPONSE:
            int code = error.response.statusCode;
            if (code >= 400 && code < 500) {
              error.message = "客户端错误的请求";
            } else if (code >= 500 && code < 700) {
              error.message = "服务器发生错误";
            }
            break;
        }
        return error;
      },
      iterable: <Interceptor>[
        InterceptorsWrapper(onRequest: (RequestOptions options) {
          print("head test");
          options.headers["MyHead"] = "head test";
        }),
        LogInterceptor(
            responseBody: false,
            requestHeader: !inProduction,
            request: !inProduction,
            requestBody: !inProduction,
            responseHeader: !inProduction,
            error: !inProduction),
        //CookieManager(CookieJar())
      ]);
  print(4);
  var l = ()=>List<Person>();
  final myService = chopper.service<MyService>(MyService);

  final response = await myService.getResourceAll4(UploadFileInfo(File(""), "1"));
  response.listen((p) {
    print(p["name"].p.p2.name);
  }, onError: (e) {
    print("onError $e");
  });
//
//  final response2 = await myService.getResourceAll23();
//  response2.listen((p) {
//    print(p.body.name);
//    print(p.body.p2.name);
//    //print(p.body.p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });

//  final response4 = await myService.getResourceAll71();
//  response4.listen((p) {
//    print(p.p2[0].name);
//    //print(p[1].p2.name);
//    //print(p.body.p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });

//  final response3 = await myService.getResourceAll3();
//  response3.listen((p) {
//    print(p.body.name);
//    print(p.body.p2.name);
//    //print(p.body.p.p2.name);
//  }, onError: (e) {
//    print("onError $e");
//  });
//
//  myService.getResourceAll5().listen((d) {
//    print(d[0].name);
//  });
//
//  //Person<Person3, Per..n()son3>()..p=Person3();
//
//  List<int> l = [1, 2, 3];
//  print(l is List);


  chopper.dispose();
}

class MockAdapter extends HttpClientAdapter {
  static const String mockHost = "mockserver";
  static const String mockBase = "http://$mockHost";
  DefaultHttpClientAdapter _defaultHttpClientAdapter =
  DefaultHttpClientAdapter();

  @override
  Future<ResponseBody> fetch(RequestOptions options,
      Stream<List<int>> requestStream, Future cancelFuture) async {
    Uri uri = options.uri;
//    if (uri.host == mockHost) {
//      print(uri.path);
//      switch (uri.path) {
//        case "/test":
//          return ResponseBody.fromString(
//            jsonEncode({
//              "index": 0,
//              "name": "mock",//{"path": uri.path}
//              "p":{
//                "index": 1,
//                "name": "mock2----",//{"path": uri.path}
//                 "p2":{
//                    "index": 1,
//                    "name": "mock3----2222222--",//{"path": uri.path}
//                  }
//              },
//              "p2":{
//                "index": 1,
//                "name": "mock344444------",//{"path": uri.path}
//              }
//            }),
//            200,
//            DioHttpHeaders.fromMap({
//              HttpHeaders.contentTypeHeader: ContentType.json,
//            }),
//          );
//        case "/test2":
//          return ResponseBody.fromString(
//            jsonEncode({
//              "name": {
//                "p":{
//                  "index": 1,
//                  "name": "mock2----",//{"path": uri.path}
//                  "p2":{
//                    "index": 1,
//                    "name": "mock3---vvvvv---",//{"path": uri.path}
//                  }
//                },
//                "p2":{
//                  "index": 1,
//                  "name": "mock3------",//{"path": uri.path}
//                }
//              },//{"path": uri.path}
//            }),
//            200,
//            DioHttpHeaders.fromMap({
//              HttpHeaders.contentTypeHeader: ContentType.json,
//            }),
//          );
//        case "/test12":
//          return ResponseBody.fromString(
//            jsonEncode({
//              "index": 0,
//              "name": "mock",//{"path": uri.path}
//
//              "p2":null,
//            }),
//            200,
//            DioHttpHeaders.fromMap({
//              HttpHeaders.contentTypeHeader: ContentType.json,
//            }),
//          );
//        case "/test42":
//          return ResponseBody.fromString(
//            jsonEncode({
//              "name":{
//                "index": 1,
//                "name": "mock344444------",//{"path": uri.path}
//                "hh":"---"
//              }
//            }),
//            200,
//            DioHttpHeaders.fromMap({
//              HttpHeaders.contentTypeHeader: ContentType.json,
//            }),
//          );
//        case "/test71":
//          return ResponseBody.fromString(
//            jsonEncode({
//              "name":"",
//              "p2":[{
//                "name":"hhhh"
//              }]
//            }),
//            200,
//            DioHttpHeaders.fromMap({
//              HttpHeaders.contentTypeHeader: ContentType.json,
//            }),
//          );
//        case "/test4":
//          return ResponseBody.fromString(
//            jsonEncode([{
//              "index": 0,
//              "name": "mock",//{"path": uri.path}
//              "p":{
//                "index": 1,
//                "name": "mocddddk344444------",//{"path": uri.path}
//              },
//              "p2":{
//                "index": 1,
//                "name": "mock344444------",//{"path": uri.path}
//              }
//            }, {
//              "index": 0,
//              "name": "4mock",//{"path": uri.path}
//              "p":{
//                "index": 1,
//                "name": "3mocddddk344444------",//{"path": uri.path}
//              },
//              "p2":{
//                "index": 1,
//                "name": "3mock344444------",//{"path": uri.path}
//              }
//            }]),
//            200,
//            DioHttpHeaders.fromMap({
//              HttpHeaders.contentTypeHeader: ContentType.json,
//            }),
//          );
//        case "/download":
//          return ResponseBody(
//            File("./README.MD").openRead(),
//            200,
//            DioHttpHeaders.fromMap({
//              HttpHeaders.contentLengthHeader: File("./README.MD").lengthSync(),
//            }),
//          );
//
//        case "/token":
//          {
//            var t = "ABCDEFGHIJKLMN".split("")..shuffle();
//            return ResponseBody.fromString(
//              jsonEncode({
//                "errCode": 0,
//                "data": {"token": t.join()}
//              }),
//              200,
//              DioHttpHeaders.fromMap({
//                HttpHeaders.contentTypeHeader: ContentType.json,
//              }),
//            );
//          }
//        default:
//          return ResponseBody.fromString("", 404, DioHttpHeaders());
//      }
//    }
    return _defaultHttpClientAdapter.fetch(
        options, requestStream, cancelFuture);
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  okdio: ^0.0.2

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:okdio/okdio.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
22
Health:
Code health derived from static analysis. [more]
89
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
55
Learn more about scoring.

We analyzed this package on Aug 18, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.4.0
  • pana: 0.12.19

Platforms

Detected platforms: Flutter, other

Primary library: package:okdio/okdio.dart with components: io.

Health suggestions

Fix lib/src/annotations.dart. (-6.31 points)

Analysis of lib/src/annotations.dart reported 13 hints, including:

line 15 col 17: Use = to separate a named parameter from its default value.

line 77 col 39: Use = to separate a named parameter from its default value.

line 77 col 58: Use = to separate a named parameter from its default value.

line 84 col 25: Use = to separate a named parameter from its default value.

line 84 col 59: Use = to separate a named parameter from its default value.

Fix lib/src/request.dart. (-3.45 points)

Analysis of lib/src/request.dart reported 7 hints, including:

line 1 col 8: Unused import: 'dart:async'.

line 25 col 20: Use = to separate a named parameter from its default value.

line 26 col 17: Use = to separate a named parameter from its default value.

line 27 col 19: Use = to separate a named parameter from its default value.

line 28 col 15: Use = to separate a named parameter from its default value.

Fix lib/src/base.dart. (-1.49 points)

Analysis of lib/src/base.dart reported 3 hints:

line 46 col 17: Use = to separate a named parameter from its default value.

line 52 col 38: Use = to separate a named parameter from its default value.

line 74 col 28: The method '_decodeResponse' isn't used.

Fix lib/src/response.dart. (-0.50 points)

Analysis of lib/src/response.dart reported 1 hint:

line 16 col 36: Avoid shadowing type parameters.

Format lib/src/interceptor.dart.

Run dartfmt to format lib/src/interceptor.dart.

Maintenance suggestions

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
dio ^2.1.10 2.1.13
dson ^0.15.5 0.15.6
logging ^0.11.3 0.11.3+2
meta ^1.1.6 1.1.7
rxdart ^0.22.0 0.22.1+1
Transitive dependencies
analyzer 0.36.4 0.38.0
args 1.5.2
async 2.3.0
build 1.1.6
built_mirrors_core 0.10.5
charcode 1.1.2
collection 1.14.12
convert 2.1.1
cookie_jar 1.0.1
crypto 2.1.1+1
csslib 0.16.1
dart_style 1.2.9
dson_core 0.15.6
front_end 0.1.19 0.1.22
glob 1.1.7
html 0.14.0+2
kernel 0.3.19 0.3.22
package_config 1.1.0
path 1.6.4
pedantic 1.8.0+1
pub_semver 1.4.2
serializable_core 0.11.3
source_gen 0.9.4+3
source_span 1.5.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
watcher 0.9.7+12
yaml 2.1.16
Dev dependencies
build_runner ^1.0.0
build_web_compilers any
coverage ^0.12.2
okdio_generator
test ^1.3.0