【问题标题】:Accessing the Rocket 0.4 database connection pool in a request guard在请求保护中访问 Rocket 0.4 数据库连接池
【发布时间】:2019-08-07 12:57:44
【问题描述】:

我正在创建一个使用 Rocket 进行身份验证的 webapp。为此,我创建了一个实现FromRequestUser 结构。它采用授权标头,其中包含 JSON Web 令牌。我反序列化此令牌以获取有效负载,然后从数据库中查询用户。这意味着FromRequest 实现需要diesel::PgConnection。在 Rocket 0.3 中,这意味着调用 PgConnection::establish,但在 Rocket 0.4 中,我们可以访问连接池。通常我会按如下方式访问这个连接池:

fn get_data(conn: db::MyDatabasePool) -> MyModel {
    MyModel::get(&conn)
}

但是,在 FromRequest 的 impl 块中,我不能只将 conn 参数添加到 from_request 函数的参数列表中。如何在请求保护之外访问我的连接池?

【问题讨论】:

    标签: rust rust-diesel rust-rocket


    【解决方案1】:

    火箭guide for database state 说:

    当需要连接到数据库时,使用您的 [数据库池] 类型作为请求保护

    由于可以通过FromRequest 创建数据库池并且您正在实现FromRequest,因此请通过DbPool::from_request(request) 使用现有实现:

    use rocket::{
        request::{self, FromRequest, Request},
        Outcome,
    };
    
    // =====
    // This is a dummy implementation of a pool
    // Refer to the Rocket guides for the correct way to do this
    struct DbPool;
    
    impl<'a, 'r> FromRequest<'a, 'r> for DbPool {
        type Error = &'static str;
    
        fn from_request(_: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
            Outcome::Success(Self)
        }
    }
    // =====
    
    struct MyDbType;
    
    impl MyDbType {
        fn from_db(_: &DbPool) -> Self {
            Self
        }
    }
    
    impl<'a, 'r> FromRequest<'a, 'r> for MyDbType {
        type Error = &'static str;
    
        fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
            let pool = DbPool::from_request(request);
            pool.map(|pool| MyDbType::from_db(&pool))
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多