body_parser 1.1.1

body_parser #

Pub build status

Parse request bodies and query strings in Dart, as well multipart/form-data uploads. No external dependencies required.

This is the request body parser powering the Angel framework. If you are looking for a server-side solution with dependency injection, WebSockets, and more, then I highly recommend it as your first choice. Bam!

Contents #

About #

I needed something like Express.js's body-parser module, so I made it here. It fully supports JSON requests. x-www-form-urlencoded fully supported, as well as query strings. You can also include arrays in your query, in the same way you would for a PHP application. Full file upload support will also be present by the production 1.0.0 release.

A benefit of this is that primitive types are automatically deserialized correctly. As in, if you have a hello=1.5 request, then body['hello'] will equal 1.5 and not '1.5'. A very semantic difference, yes, but it relieves stress in my head.

Installation #

To install Body Parser for your Dart project, simply add body_parser to your pub dependencies.

dependencies:
    body_parser: any

Usage #

Body Parser exposes a simple class called BodyParseResult. You can easily parse the query string and request body for a request by calling Future<BodyParseResult> parseBody.

import 'dart:convert';
import 'package:body_parser/body_parser.dart';

main() async {
    // ...
    await for (HttpRequest request in server) {
      request.response.write(JSON.encode(await parseBody(request).body));
      await request.response.close();
    }
}

You can also use buildMapFromUri(Map, String) to populate a map from a URL encoded string.

This can easily be used with a library like JSON God to build structured JSON/REST APIs. Add validation and you've got an instant backend.

MyClass create(HttpRequest request) async {
    return god.deserialize(await parseBody(request).body, MyClass);
}

Custom Body Parsing #

In cases where you need to parse unrecognized content types, body_parser won't be of any help to you on its own. However, you can use the originalBuffer property of a BodyParseResult to see the original request buffer. To get this functionality, pass storeOriginalBuffer as true when calling parseBody.

For example, if you wanted to parse GraphQL queries within your server...

app.get('/graphql', (req, res) async {
  if (req.headers.contentType.mimeType == 'application/graphql') {
    var graphQlString = new String.fromCharCodes(req.originalBuffer);
    // ...
  }
});

1.1.1 #

  • Dart 2 updates; should fix Angel in Travis.

1.1.0 #

  • Add parseBodyFromStream

example/main.dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'package:body_parser/body_parser.dart';

main() async {
  var address = '127.0.0.1';
  var port = 3000;
  var futures = <Future>[];

  for (int i = 1; i < Platform.numberOfProcessors; i++) {
    futures.add(Isolate.spawn(start, [address, port, i]));
  }

  Future.wait(futures).then((_) {
    print('All instances started.');
    print(
        'Test with "wrk -t12 -c400 -d30s -s ./example/post.lua http://localhost:3000" or similar');
    start([address, port, 0]);
  });
}

void start(List args) {
  var address = new InternetAddress(args[0] as String);
  int port = args[1], id = args[2];

  HttpServer.bind(address, port, shared: true).then((server) {
    server.listen((request) async {
      // ignore: deprecated_member_use
      var body = await parseBody(request);
      request.response
        ..headers.contentType = new ContentType('application', 'json')
        ..write(json.encode(body.body))
        ..close();
    });

    print(
        'Server #$id listening at http://${server.address.address}:${server.port}');
  });
}

Use this package as a library

1. Depend on it

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


dependencies:
  body_parser: ^1.1.1

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:body_parser/body_parser.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
64
Health:
Code health derived from static analysis. [more]
92
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
79
Learn more about scoring.

We analyzed this package on Jul 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:body_parser/body_parser.dart with components: io.

Health suggestions

Fix lib/src/get_value.dart. (-2.96 points)

Analysis of lib/src/get_value.dart reported 6 hints, including:

line 7 col 7: DO use curly braces for all flow control structures.

line 9 col 7: DO use curly braces for all flow control structures.

line 12 col 7: DO use curly braces for all flow control structures.

line 14 col 7: DO use curly braces for all flow control structures.

line 16 col 7: DO use curly braces for all flow control structures.

Fix lib/src/parse_body.dart. (-2.96 points)

Analysis of lib/src/parse_body.dart reported 6 hints, including:

line 16 col 30: Use = to separate a named parameter from its default value.

line 36 col 30: Use = to separate a named parameter from its default value.

line 52 col 7: DO use curly braces for all flow control structures.

line 65 col 13: Future results in async function bodies must be awaited or marked unawaited using package:pedantic.

line 139 col 7: Don't explicitly initialize variables to null.

Fix lib/src/file_upload_info.dart. (-1 points)

Analysis of lib/src/file_upload_info.dart reported 2 hints:

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

line 16 col 71: Use ; instead of {} for empty constructor bodies.

Fix lib/src/map_from_uri.dart. (-1 points)

Analysis of lib/src/map_from_uri.dart reported 2 hints:

line 39 col 9: DO use curly braces for all flow control structures.

line 41 col 7: DO use curly braces for all flow control structures.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.8.0 <3.0.0
dart2_constant ^1.0.0 1.0.2+dart2
http_parser >=3.1.1 <4.0.0 3.1.3
http_server >=0.9.6 <1.0.0 0.9.8+3
mime >=0.9.3 <1.0.0 0.9.6+3
Transitive dependencies
charcode 1.1.2
collection 1.14.11
meta 1.1.7
path 1.6.2
source_span 1.5.5
string_scanner 1.0.4
term_glyph 1.1.0
typed_data 1.1.6
Dev dependencies
http >=0.11.3 <0.12.0
test >=0.12.15

Admin