diff --git a/actix-session/CHANGES.md b/actix-session/CHANGES.md index a60d1e668..8e06a5624 100644 --- a/actix-session/CHANGES.md +++ b/actix-session/CHANGES.md @@ -1,5 +1,9 @@ # Changes +## [0.1.0-beta.2] - 2019-04-28 + +* Add helper trait `UserSession` which allows to get session for ServiceRequest and HttpRequest + ## [0.1.0-beta.1] - 2019-04-20 * Update actix-web to beta.1 diff --git a/actix-session/src/lib.rs b/actix-session/src/lib.rs index b82029647..0e7831442 100644 --- a/actix-session/src/lib.rs +++ b/actix-session/src/lib.rs @@ -79,6 +79,23 @@ pub use crate::cookie::CookieSession; /// ``` pub struct Session(Rc>); +/// Helper trait that allows to get session +pub trait UserSession { + fn get_session(&mut self) -> Session; +} + +impl UserSession for HttpRequest { + fn get_session(&mut self) -> Session { + Session::get_session(&mut *self.extensions_mut()) + } +} + +impl UserSession for ServiceRequest { + fn get_session(&mut self) -> Session { + Session::get_session(&mut *self.extensions_mut()) + } +} + #[derive(Default)] struct SessionInner { state: HashMap, @@ -208,4 +225,18 @@ mod tests { let changes: Vec<_> = Session::get_changes(&mut res).unwrap().collect(); assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]); } + + #[test] + fn get_session() { + let mut req = test::TestRequest::default().to_srv_request(); + + Session::set_session( + vec![("key".to_string(), "\"value\"".to_string())].into_iter(), + &mut req, + ); + + let session = req.get_session(); + let res = session.get::("key").unwrap(); + assert_eq!(res, Some("value".to_string())); + } }