Giter Club home page Giter Club logo

http_extensions's Introduction

http_extensions

A set of extensions for the http dart package.

http_extensions's People

Contributors

acoutts avatar aloisdeniel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

http_extensions's Issues

Query Parameters Extension

I was trying to figure out the best way to append query parameters with each request and ending up creating an extension. Here is what I put together.

Extension (request_extension.dart)

class RequestExtension extends Extension<RequestOptions> {
  final Logger logger;

  RequestExtension({RequestOptions defaultOptions = const RequestOptions(), this.logger})
      : super(defaultOptions: defaultOptions);

  Future<BaseRequest> _resolve(
      BaseRequest original, RequestOptions options) async {
    if (original is ExtensionRequest) {
      return ExtensionRequest(
          request: await _resolve(original.request, options),
          options: original.options);
    }

    if (original.url.hasScheme) {
      return original;
    }

    if (options.queryParameters == null) {
      return original;
    }

    if (options.queryParameters.isNotEmpty) {
      final url = original.url.replace(queryParameters: options.queryParameters);

      logger?.fine('Appended Query Parameters');

      if (original is Request) {
        var result = Request(original.method, url);
        if (original.headers != null) result.headers.addAll(original.headers);
        if (original.encoding != null) result.encoding = original.encoding;
        if (original.bodyBytes != null) result.bodyBytes = original.bodyBytes;

        return result;
      }

      if (original is StreamedRequest) {
        var result = Request(original.method, url);
        if (original.headers != null) result.headers.addAll(original.headers);
        result.bodyBytes = await original.finalize().toBytes();

        return result;
      }

      throw ArgumentError(
          "Failed to resolve request of type ${original.runtimeType}");
    } else {
      return original;
    }
  }

  @override
  Future<StreamedResponse> sendWithOptions(
      BaseRequest request, RequestOptions options) async {
    request = await _resolve(request, options);
    return await super.sendWithOptions(request, options);
  }
}

Options (request_options.dart)

class RequestOptions {
  final Map<String, String> queryParameters;

  const RequestOptions({this.queryParameters});
}

Example (main.dart)

Future main() async {
  final client = ExtendedClient(
    inner: Client(),
    extensions: [
      RequestExtension(),
    ],
  );

  var response = await client.getWithOptions('my-url-string', 
    options: [RequestOptions(queryParameters: {'option1': 'value1'}]);
}

Not sure if this is the best way to do this, you could I imagine add a parameter on each method call (get, put, delete, etc.) for the query params.

protobuf version need to update

The latest protobuf version is 1.0.1

In my project,when " pub get ",get this error:

Because every version of http_extensions_protobuf depends on protobuf ^0.13.12 and startupnamer depends on protobuf ^1.0.1, http_extensions_protobuf is forbidden.

Support for Multipart requests

Hey @aloisdeniel

I noticed there is currently no support for Multipart request. I went ahead and added an extension to the extension. :)

extension ExtendedClientX on ExtendedClient {
  Future<http.Response> formWithOptions(
    String url, {
    @required Map<String, dynamic> data,
    Map<String, io.File> files,
    Map<String, String> headers,
    List<dynamic> options,
  }) async {
    assert(data != null);
    final request = http.MultipartRequest("POST", Uri.parse(url));

    request.fields..addAll(_encodeFormBody(data));

    if (files != null) {
      for (final item in files.entries) {
        request.files.add(
          await http.MultipartFile.fromPath(item.key, item.value.path),
        );
      }
    }

    return sendWithOptions(
      request,
      <dynamic>[
        ...options,
        JsonRequestOptions({...headers, io.HttpHeaders.contentTypeHeader: "application/x-www-form-urlencoded"})
      ],
    ).then(http.Response.fromStream);
  }

  String encodeBody(dynamic value) => json.encode(value);

  Map<String, String> _encodeFormBody(Map<String, dynamic> data) {
    return data.map((key, dynamic value) => MapEntry(key, _isPrimitiveValue(value) ? value : encodeBody(value)));
  }

  bool _isPrimitiveValue(dynamic value) {
    return [int, double, bool, String].contains(value.runtimeType);
  }
}

And another helper extension for sugar.

class JsonRequestOptions {
  const JsonRequestOptions([this.headers = const {}]);

  final Map<String, String> headers;
}

class JsonRequestExtension extends Extension<JsonRequestOptions> {
  JsonRequestExtension([
    JsonRequestOptions defaultOptions = const JsonRequestOptions(
      {io.HttpHeaders.acceptHeader: mime, io.HttpHeaders.contentTypeHeader: mime},
    ),
  ]) : super(defaultOptions: defaultOptions);

  static const mime = "application/json";

  @override
  Future<http.StreamedResponse> sendWithOptions(http.BaseRequest request, JsonRequestOptions options) {
    final headers = Map<String, String>.from(defaultOptions.headers);
    if (options.headers != null && options.headers.isNotEmpty) {
      headers.addAll(options.headers);
    }
    if (headers.isNotEmpty) {
      request.headers.addAll(headers);
    }
    return super.sendWithOptions(request, options);
  }
}

This seemed to cover all my cases, tests passed and all.

Then, I also found the retry extension useful and realised I needed it too. Only issue now is the _copyRequest method. This eagerly tries to make a copy of the BaseRequest. As that is the only supported variant, it completely ignores the files and fields property of the multipart request. To solve this, we would need a more elegant approach. Hence the long story.

Also, nice work with the extensions. 👍

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.