Expose active 'Rocket' via 'Request::rocket()'.

This commit is contained in:
Sergio Benitez 2021-03-25 18:33:15 -07:00
parent 9cb2552055
commit 630a458417
9 changed files with 34 additions and 33 deletions

View File

@ -177,7 +177,7 @@ impl<'r, K: 'static, C: Poolable> FromRequest<'r> for Connection<K, C> {
#[inline]
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, ()> {
match request.managed_state::<ConnectionPool<K, C>>() {
match request.rocket().state::<ConnectionPool<K, C>>() {
Some(c) => c.get().await.into_outcome(Status::ServiceUnavailable),
None => {
error_!("Missing database fairing for `{}`", std::any::type_name::<K>());

View File

@ -185,7 +185,7 @@ impl Fairing for TemplateFairing {
#[cfg(debug_assertions)]
async fn on_request(&self, req: &mut rocket::Request<'_>, _data: &mut rocket::Data) {
let cm = req.managed_state::<ContextManager>()
let cm = req.rocket().state::<ContextManager>()
.expect("Template ContextManager registered in on_attach");
cm.reload_if_needed(&self.callback);

View File

@ -420,7 +420,7 @@ impl Template {
impl<'r> Responder<'r, 'static> for Template {
fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
let (render, content_type) = {
let ctxt = req.managed_state::<ContextManager>().ok_or_else(|| {
let ctxt = req.rocket().state::<ContextManager>().ok_or_else(|| {
error_!("Uninitialized template context: missing fairing.");
info_!("To use templates, you must attach `Template::fairing()`.");
info_!("See the `Template` documentation for more information.");

View File

@ -384,7 +384,7 @@ impl<'r> FromRequest<'r> for &'r Config {
type Error = std::convert::Infallible;
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
request::Outcome::Success(req.config())
request::Outcome::Success(req.rocket().config())
}
}

View File

@ -186,7 +186,7 @@ impl<'r> FromRequest<'r> for &'r SecretKey {
type Error = std::convert::Infallible;
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
Outcome::Success(&req.config().secret_key)
Outcome::Success(&req.rocket().config().secret_key)
}
}

View File

@ -305,7 +305,7 @@ impl<'v> TempFile<'v> {
.or_else(|| req.limits().get("file"))
.unwrap_or(Limits::FILE);
let temp_dir = req.config().temp_dir.clone();
let temp_dir = req.rocket().config().temp_dir.clone();
let file = tokio::task::spawn_blocking(move || {
NamedTempFile::new_in(temp_dir)
}).await.map_err(|_| {

View File

@ -88,7 +88,7 @@ impl<'c> LocalResponse<'c> {
async move {
let response: Response<'c> = f(request).await;
let mut cookies = CookieJar::new(request.config());
let mut cookies = CookieJar::new(request.rocket().config());
for cookie in response.cookies() {
cookies.add_original(cookie.into_owned());
}

View File

@ -468,22 +468,40 @@ impl<'r> Request<'r> {
}
}
/// Returns the Rocket server configuration.
/// Returns the [`Rocket`] instance that is handling this request.
///
/// # Example
///
/// ```rust
/// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
/// # let request = c.get("/");
/// let config = request.config();
/// # type Pool = usize;
/// // Retrieve the application config via `Rocket::config()`.
/// let config = request.rocket().config();
///
/// // Retrieve managed state via `Rocket::state()`.
/// let state = request.rocket().state::<Pool>();
///
/// // Get a list of all of the registered routes and catchers.
/// let routes = request.rocket().routes();
/// let catchers = request.rocket().catchers();
/// ```
#[inline(always)]
pub fn config(&self) -> &'r Config {
&self.state.rocket.config
pub fn rocket(&self) -> &'r Rocket {
&self.state.rocket
}
/// Returns the configured application data limits.
///
/// This is convenience function equivalent to:
///
/// ```rust
/// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
/// # let request = c.get("/");
/// &request.rocket().config().limits
/// # ;
/// ```
///
/// # Example
///
/// ```rust
@ -499,7 +517,7 @@ impl<'r> Request<'r> {
/// ```
#[inline(always)]
pub fn limits(&self) -> &'r Limits {
&self.config().limits
&self.rocket().config().limits
}
/// Get the presently matched route, if any.
@ -541,23 +559,6 @@ impl<'r> Request<'r> {
T::from_request(self)
}
/// Retrieve managed state.
///
/// # Example
///
/// ```rust
/// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
/// # let request = c.get("/");
/// # type Pool = usize;
/// let pool = request.managed_state::<Pool>();
/// ```
#[inline(always)]
pub fn managed_state<T>(&self) -> Option<&'r T>
where T: Send + Sync + 'static
{
self.state.rocket.state::<T>()
}
/// Retrieves the cached value for type `T` from the request-local cached
/// state of `self`. If no such value has previously been cached for this
/// request, `f` is called to produce the value which is subsequently

View File

@ -54,8 +54,8 @@ use crate::http::Status;
///
/// Because `State` is itself a request guard, managed state can be retrieved
/// from another request guard's implementation using either
/// [`Request::guard()`] or [`Request::managed_state()`]. In the following code
/// example, the `Item` request guard retrieves `MyConfig` from managed state:
/// [`Request::guard()`] or [`Rocket::state()`]. In the following code example,
/// the `Item` request guard retrieves `MyConfig` from managed state:
///
/// ```rust
/// use rocket::State;
@ -75,7 +75,7 @@ use crate::http::Status;
/// .map(|my_config| Item(&my_config.inner().user_val));
///
/// // Or alternatively, using `Request::managed_state()`:
/// let outcome = request.managed_state::<MyConfig>()
/// let outcome = request.rocket().state::<MyConfig>()
/// .map(|my_config| Item(&my_config.user_val))
/// .or_forward(());
///
@ -174,7 +174,7 @@ impl<'r, T: Send + Sync + 'static> FromRequest<'r> for State<'r, T> {
#[inline(always)]
async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, ()> {
match req.managed_state::<T>() {
match req.rocket().state::<T>() {
Some(state) => Outcome::Success(State(state)),
None => {
error_!("Attempted to retrieve unmanaged state `{}`!", std::any::type_name::<T>());