Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a trait FromRequest #398

Closed
kdy1 opened this issue Jan 20, 2020 · 2 comments
Closed

Add a trait FromRequest #398

kdy1 opened this issue Jan 20, 2020 · 2 comments

Comments

@kdy1
Copy link

kdy1 commented Jan 20, 2020

With the help of a proc macro (#395), such trait will be very useful. I'm currently experimenting with it at kdy1/rweb#5.

Trait definition will be

pub trait FromRequest: Sized {
    type Filter: Filter<Extract = (Self,), Error = Rejection>;

    fn new() -> Self::Filter;
}

and this trait should be exposed, thus the user can implement it. Type inference is not a problem at all, as proc macro suggested by #395 can insert a fully qualified path.

use rweb::{filters::BoxedFilter, *};

impl FromRequest for User {
    type Filter = BoxedFilter<(User,)>;

    fn new() -> Self::Filter {
        // In real world, this can be changed to use Authorization header
        header::<String>("x-user-id").map(|id| User { id }).boxed()
    }
}

struct User {
    id: String,
}

#[get("/")]
fn index(user: User) -> String {
    user.id
}

It also allows using filters::ws::Ws without any annotation and provides more natural syntax for forms.

#[post("/json")]
fn json(body: Json<LoginForm>) -> Result<String, Error> {
    Ok(serde_json::to_string(&body).unwrap())
}

looks much more natural than

#[post("/json")]
fn json(#[json] body: LoginForm) -> Result<String, Error> {
    Ok(serde_json::to_string(&body).unwrap())
}
@seanmonstar seanmonstar changed the title Add a trait FromRequst Add a trait FromRequest Jan 24, 2020
@seanmonstar
Copy link
Owner

Is such a trait actually required in warp, or can the macros crate just provide it?

@kdy1
Copy link
Author

kdy1 commented Jan 24, 2020

Is such a trait actually required in warp, or can the macros crate just provide it?

It should be supported by runtime. Being in warp does not matter.

@jxs jxs closed this as completed Jul 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants