Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(axum-extra): add trait GetCachedFromRef to get cached value #2925

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion axum-extra/src/extract/cached.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use axum::{
async_trait,
extract::{Extension, FromRequestParts},
extract::{Extension, FromRequestParts, Request},
};
use http::request::Parts;

Expand Down Expand Up @@ -83,6 +83,53 @@ use http::request::Parts;
#[derive(Debug, Clone, Default)]
pub struct Cached<T>(pub T);

impl<T> Cached<T> {
fn from_http_extensions(extensions: &http::Extensions) -> Option<Cached<T>>
where
T: Clone + Send + Sync + 'static,
{
extensions
.get::<CachedEntry<T>>()
.cloned()
.map(|CachedEntry(value)| Self(value))
}
}

/// The [`GetCachedFromRef`] trait provides a way to retrieve a [`Cached`] value from a reference.
///
/// This trait is designed to be used when you want to access previously cached value.
pub trait GetCachedFromRef<T> {
/// Get cached value from a reference.
fn get_cached(&self) -> Option<Cached<T>>;
}

impl<T> GetCachedFromRef<T> for http::Extensions
where
T: Clone + Send + Sync + 'static,
{
fn get_cached(&self) -> Option<Cached<T>> {
Cached::from_http_extensions(self)
}
}

impl<T> GetCachedFromRef<T> for Parts
where
T: Clone + Send + Sync + 'static,
{
fn get_cached(&self) -> Option<Cached<T>> {
Cached::from_http_extensions(&self.extensions)
}
}

impl<T> GetCachedFromRef<T> for Request
where
T: Clone + Send + Sync + 'static,
{
fn get_cached(&self) -> Option<Cached<T>> {
Cached::from_http_extensions(self.extensions())
}
}

#[derive(Clone)]
struct CachedEntry<T>(T);

Expand Down
6 changes: 5 additions & 1 deletion axum-extra/src/extract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ mod query;
#[cfg(feature = "multipart")]
pub mod multipart;

pub use self::{cached::Cached, optional_path::OptionalPath, with_rejection::WithRejection};
pub use self::{
cached::{Cached, GetCachedFromRef},
optional_path::OptionalPath,
with_rejection::WithRejection,
};

#[cfg(feature = "cookie")]
pub use self::cookie::CookieJar;
Expand Down