我正在创建一个使用Rocket进行身份验证的webapp。为此,我创建了一个实现User
的FromRequest
结构。它采用授权头,其中包含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
函数的参数列表中。如何在请求保护之外访问我的连接池?
每当需要连接到数据库时,请使用[数据库池]类型作为请求保护
由于可以通过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))
}
}