From 5877dfc5d668fdca9e6a175f82557e691ab000ab Mon Sep 17 00:00:00 2001 From: 3moredays Date: Sun, 22 Sep 2024 17:17:46 +0800 Subject: [PATCH] feat: add trait GetCachedFromRef to get cached value --- axum-extra/src/extract/cached.rs | 49 +++++++++++++++++++++++++++++++- axum-extra/src/extract/mod.rs | 6 +++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/axum-extra/src/extract/cached.rs b/axum-extra/src/extract/cached.rs index f9714eb014..86db65523a 100644 --- a/axum-extra/src/extract/cached.rs +++ b/axum-extra/src/extract/cached.rs @@ -1,6 +1,6 @@ use axum::{ async_trait, - extract::{Extension, FromRequestParts}, + extract::{Extension, FromRequestParts, Request}, }; use http::request::Parts; @@ -83,6 +83,53 @@ use http::request::Parts; #[derive(Debug, Clone, Default)] pub struct Cached(pub T); +impl Cached { + fn from_http_extensions(extensions: &http::Extensions) -> Option> + where + T: Clone + Send + Sync + 'static, + { + extensions + .get::>() + .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 { + /// Get cached value from a reference. + fn get_cached(&self) -> Option>; +} + +impl GetCachedFromRef for http::Extensions +where + T: Clone + Send + Sync + 'static, +{ + fn get_cached(&self) -> Option> { + Cached::from_http_extensions(self) + } +} + +impl GetCachedFromRef for Parts +where + T: Clone + Send + Sync + 'static, +{ + fn get_cached(&self) -> Option> { + Cached::from_http_extensions(&self.extensions) + } +} + +impl GetCachedFromRef for Request +where + T: Clone + Send + Sync + 'static, +{ + fn get_cached(&self) -> Option> { + Cached::from_http_extensions(self.extensions()) + } +} + #[derive(Clone)] struct CachedEntry(T); diff --git a/axum-extra/src/extract/mod.rs b/axum-extra/src/extract/mod.rs index 1f9974de02..964ab533e8 100644 --- a/axum-extra/src/extract/mod.rs +++ b/axum-extra/src/extract/mod.rs @@ -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;