use crate::Session;
use std::sync::Arc;
use wae_types::WaeError;
#[derive(Debug, Clone)]
pub struct SessionRejection {
inner: WaeError,
}
impl SessionRejection {
fn new(error: WaeError) -> Self {
Self { inner: error }
}
pub fn into_inner(self) -> WaeError {
self.inner
}
}
impl std::fmt::Display for SessionRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.inner.fmt(f)
}
}
impl std::error::Error for SessionRejection {}
#[derive(Debug, Clone)]
pub struct SessionExtractor {
session: Arc<Session>,
}
impl SessionExtractor {
pub fn new(session: Arc<Session>) -> Self {
Self { session }
}
pub fn from_request<B>(request: &http::Request<B>) -> Result<Self, SessionRejection> {
request
.extensions()
.get::<Arc<Session>>()
.cloned()
.map(|session| SessionExtractor { session })
.ok_or_else(|| SessionRejection::new(WaeError::internal("Session not found in request extensions")))
}
pub fn inner(&self) -> &Session {
&self.session
}
pub fn id(&self) -> &str {
self.session.id()
}
pub fn is_new(&self) -> bool {
self.session.is_new()
}
pub async fn get(&self, key: &str) -> Option<serde_json::Value> {
self.session.get(key).await
}
pub async fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.session.get_typed(key).await
}
pub async fn set<T: serde::Serialize>(&self, key: impl Into<String>, value: T) {
self.session.set(key, value).await
}
pub async fn remove(&self, key: &str) -> Option<serde_json::Value> {
self.session.remove(key).await
}
pub async fn contains(&self, key: &str) -> bool {
self.session.contains(key).await
}
pub async fn clear(&self) {
self.session.clear().await
}
pub async fn keys(&self) -> Vec<String> {
self.session.keys().await
}
pub async fn len(&self) -> usize {
self.session.len().await
}
pub async fn is_empty(&self) -> bool {
self.session.is_empty().await
}
}