1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-23 23:51:06 +01:00

Add helper trait UserSession which allows to get session for ServiceRequest and HttpRequest

This commit is contained in:
Nikolay Kim 2019-04-28 09:08:51 -07:00
parent 70a4c36496
commit ffd2c04cd3
2 changed files with 35 additions and 0 deletions

View File

@ -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

View File

@ -79,6 +79,23 @@ pub use crate::cookie::CookieSession;
/// ```
pub struct Session(Rc<RefCell<SessionInner>>);
/// 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<String, String>,
@ -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::<String>("key").unwrap();
assert_eq!(res, Some("value".to_string()));
}
}