Skip to content

Commit

Permalink
feat: add trait GetCachedFromRef to get cached value
Browse files Browse the repository at this point in the history
  • Loading branch information
azureqaq committed Sep 22, 2024
1 parent 2fe4351 commit 4f637c9
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
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 retrive a [`Cached`] value from a reference.

Check warning on line 98 in axum-extra/src/extract/cached.rs

View workflow job for this annotation

GitHub Actions / Spell Check with Typos

"retrive" should be "retrieve".
///
/// 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

0 comments on commit 4f637c9

Please sign in to comment.