Actix -> Using from_request inside another implementor of FromRequest

Hello,

can anyone point me to an actix example for calling a from_request implementation inside another from_request implementation?

use futures::future::{Ready, ok, err};
use actix_web::{FromRequest, Error, HttpRequest};
use actix_identity::Identity;
use actix_web::error::ErrorBadRequest;
use rand;
use actix_web::dev::Payload;

struct Test {
    some : String
}

impl FromRequest for Test {
    type Error = Error;
    type Future = Ready<Result<Test, Error>>;
    type Config = ();

    fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
        if let Some(other) = Other::from_request(req, pl) {
            let test = Test {
                some : String::from(other.more)
            };
            return ok(test);
        }
        err(ErrorBadRequest("failed"))
    }
}

struct Other {
    more : String
}

impl FromRequest for Other {
    type Error = Error;
    type Future = Ready<Result<Other, Error>>;
    type Config = ();

    fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
        /*
        ... some extraction logic
        */
        if rand::random() {
            return ok(Other{
                more : "test".to_owned()
            });
        }
        err(ErrorBadRequest("fail"))
    }
}

When trying to compile I get this error:

error[E0308]: mismatched types
  --> src/test.rs:18:16
   |
18 |         if let Some(other) = Other::from_request(req, pl) {
   |                ^^^^^^^^^^^   ---------------------------- this expression has type `futures_util::future::ready::Ready<std::result::Result<test::Other, actix_web::Error>>`
   |                |
   |                expected struct `futures_util::future::ready::Ready`, found enum `std::option::Option`
   |
   = note: expected struct `futures_util::future::ready::Ready<std::result::Result<test::Other, actix_web::Error>>`
                found enum `std::option::Option<_>`

My Cargo.toml looks like this:

[dependencies]
actix-web = "2.0.0"
actix-identity = "0.2.1"
futures = "0.3.4"
rand = "0.7.3"

How can I unwrap the Ready<Future<...>> non-async inside from_request ?
I so far only know how to use a FromRequest implementor as a route-fn parameter.

You can use the into_inner method to get the value inside.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.