Pragmatic post parameter handling in start

25 Feb 2014

Start is a Sinatra inspired web framework for Dart. Up to version 0.2.0 Start provided no pragmatic post parameter handling. With issue 49 I proposed a getPostParams method for the Request class.

That is how my proposal looked like:

/**
 * Method to get post parameters from a [Request] object.
 */
Future<Map<String, String>> getPostParams({ Encoding enc: UTF8 }) {
  Completer c = new Completer();
  this.input.transform(const AsciiDecoder()).listen((content) {
    final postParams = new Map.fromIterable(
        content.split("&").map((kvs) => kvs.split("=")),
        key: (kv) => Uri.decodeQueryComponent(kv[0], encoding: enc),
        value: (kv) => Uri.decodeQueryComponent(kv[1], encoding: enc)
    );
    c.complete(postParams);
  });
  return c.future;
}

This proposal has made it to Start version 0.2.1 with following commit. So with Start version 0.2.1 you can do now the following pragmatic form of post request parameter handling.

import 'package:start/start.dart';

main() {
  start(port: 3000).then((Server app) {

    [...]

    app.post("/formular").listen((Request req) {
      req.postParams().then((params) {
        final fn = params['first name'];
        final ln = params['last name'];
        req.response.send("Hello $fn $ln");
      });
    });

    [...]

  });
}

Thanks to Yehor Lvivski for providing the Sinatra inspired Start web framework and for integrating issue 49. It makes post parameter handling with Start more pragmatic.

Update

Since Start version 0.2.2 you should use payload(). By using payload you can also handle parameters provided via POST, PUT, DELETE in request body. Above mentioned parameter handling changes to:

import 'package:start/start.dart';

main() {
  start(port: 3000).then((Server app) {

    [...]

    // Since version 0.2.2 ALSO put and delete is possible here
    app.post("/formular").listen((Request req) {  
      req.payload().then((params) {
        final fn = params['first name'];
        final ln = params['last name'];
        req.response.send("Hello $fn $ln");
      });
    });

    [...]

  });
}