数据库状态的火箭指南说:
每当需要连接到数据库时,使用您的 [database pool] 类型作为请求保护
由于可以通过创建数据库池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))
}
}