rustless / rustless

REST-like API micro-framework for Rust. Works with Iron.
MIT License
618 stars 50 forks source link

Stronger parameter typing #58

Open antoine-de opened 8 years ago

antoine-de commented 8 years ago

Hi,

Don't you think it would be nice to have the possibility to type the handler parameters more ?

I really like the way rustless checks and coerces a handler parameters, but it seems they are only used to check the parameters, but in the handler, the parameters must be casted again to their right type.

It might be clearer with an example :wink::

ns.get("", |endpoint| {
            endpoint.params(|params| {
                params.req_typed("q", json_dsl::string());
                params.opt_typed("lat", json_dsl::f64());
            });
            endpoint.handle(|client, params| {
                let q = params.find("q").unwrap().as_string().unwrap().to_string(); // <- for required param we need 2 'safe' unwrap + one 'cast'
                let lat = params.find("lat").and_then(|p| p.as_f64()); // for optional params need one cast
               // do some stuff
            })
        });

I think it would be nice to give a struct representing the parameters:

struct MyParams {
    q: String,
    lat: Option<f64>
}

and then use it it in the parameter checking phase and in the handler.

we might use them like this (only a proposal):


ns.get("", |endpoint| {
            endpoint.typed_params<MyParams>();
            // we could also have mechanism to check the validity of the filled params 
            // after the construction (like mutually_exclusive mechanims):
            // endpoint.typed_params<MyParams>(|p| check(p)); // or with a Trait

            endpoint.typed_handle<MyParams>(|client, params| {
               print!("params: {}, {}", params.q, params.lat);
               // do some stuff
            })
        });

It would be really great if there was a magical way to build a MyParams from the parameters, but we could maybe add code (or a macro ?) in the typed_params method to build it.

If you like the idea, I can try to work on this, but my rust level is a bit low for the moment :confused:

s-panferov commented 8 years ago

@antoine-de I definitely like this, and I think that this can be done together with rewriting rustless to use Serde library, which is on roadmap. I'll try to implement this next week.

antoine-de commented 8 years ago

great!

I'm not completely fluent in rustless for the moment, but don't hesitate to tell me if I can land a hand (i'm on #iron on irc, name antoine_de if you want)

chpio commented 8 years ago

i think as serde now landed in rustless, we could add this feature more easily now?