Support State with #[derive(FromRequest[Parts])] (#1391)

* Support `State` with `#[derive(FromRequest[Parts])]`

Fixes https://github.com/tokio-rs/axum/issues/1314

This makes it possible to extract things via `State` in
`#[derive(FromRequet)]`:

```rust
struct Foo {
    state: State<AppState>,
}
```

The state can also be inferred in a lot of cases so you only need to
write:

```rust
struct Foo {
    // since we're using `State<AppState>` we know the state has to be
    // `AppState`
    state: State<AppState>,
}
```

Same for

```rust
struct Foo {
    #[from_request(via(State))]
    state: AppState,
}
```

And

```rust
struct AppState {}
```

I think I've covered all the edge cases but there are (unsurprisingly) a
few.

* make sure things can be combined with other extractors

* main functions in ui tests don't need to be async

* Add test for multiple identicaly state types

* Add failing test for multiple states
This commit is contained in:
David Pedersen
2022-09-23 23:50:50 +02:00
committed by GitHub
parent e3a17c1249
commit c3f3db79ec
22 changed files with 787 additions and 91 deletions
@@ -0,0 +1,22 @@
use axum_macros::FromRequest;
use axum::extract::State;
#[derive(FromRequest)]
struct Extractor {
inner_state: State<AppState>,
other_state: State<OtherState>,
}
#[derive(Clone)]
struct AppState {}
#[derive(Clone)]
struct OtherState {}
fn assert_from_request()
where
Extractor: axum::extract::FromRequest<AppState, axum::body::Body, Rejection = axum::response::Response>,
{
}
fn main() {}
@@ -0,0 +1,23 @@
error[E0277]: the trait bound `AppState: FromRef<S>` is not satisfied
--> tests/from_request/fail/state_infer_multiple_different_types.rs:6:18
|
6 | inner_state: State<AppState>,
| ^^^^^ the trait `FromRef<S>` is not implemented for `AppState`
|
= note: required because of the requirements on the impl of `FromRequestParts<S>` for `State<AppState>`
help: consider extending the `where` clause, but there might be an alternative better way to express this requirement
|
4 | #[derive(FromRequest, AppState: FromRef<S>)]
| ++++++++++++++++++++++
error[E0277]: the trait bound `OtherState: FromRef<S>` is not satisfied
--> tests/from_request/fail/state_infer_multiple_different_types.rs:7:18
|
7 | other_state: State<OtherState>,
| ^^^^^ the trait `FromRef<S>` is not implemented for `OtherState`
|
= note: required because of the requirements on the impl of `FromRequestParts<S>` for `State<OtherState>`
help: consider extending the `where` clause, but there might be an alternative better way to express this requirement
|
4 | #[derive(FromRequest, OtherState: FromRef<S>)]
| ++++++++++++++++++++++++
@@ -1,4 +1,4 @@
error: expected `via` or `rejection`
error: expected one of: `via`, `rejection`, `state`
--> tests/from_request/fail/unknown_attr_container.rs:4:16
|
4 | #[from_request(foo)]