UserM.load implemented
@@ -4,29 +4,48 @@ use futures::{future, Future};
use serde_derive::*;
use std::marker::PhantomData;
use std::rc::Rc;
+use std::cell::RefCell;
-// @TODO: auth_key, user, addons
-#[derive(Serialize, Deserialize, Clone, Debug)]
+const USER_DATA_KEY: &str = "userData";
+
+#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
struct UserData {
- auth_key: String,
- user: User,
+ // @TODO: one option which is either None or Some(authKey + user)
+ auth_key: Option<String>,
+ user: Option<User>,
addons: Vec<Descriptor>,
}
#[derive(Default)]
pub struct UserMiddleware<T: Environment> {
//id: usize,
- pub user: Option<String>,
+ state: Rc<RefCell<Option<UserData>>>,
pub env: PhantomData<T>,
}
impl<T: Environment> UserMiddleware<T> {
pub fn new() -> Self {
UserMiddleware {
- user: None,
+ state: Rc::new(RefCell::new(None)),
env: PhantomData,
}
}
+ // @TODO is there a better way to do this?
+ fn load(&mut self) -> EnvFuture<UserData> {
+ let current_state = self.state.borrow().to_owned();
+ if let Some(ud) = current_state {
+ return Box::new(future::ok(ud))
+ }
+
+ let state = self.state.clone();
+ let fut = T::get_storage(USER_DATA_KEY)
+ .and_then(move |result: Option<Box<UserData>>| {
+ let ud: UserData = *result.unwrap_or_default();
+ *state.borrow_mut() = Some(ud.to_owned());
+ future::ok(ud)
+ });
+ Box::new(fut)
+ }
}
impl<T: Environment> Handler for UserMiddleware<T> {
fn handle(&self, action: &Action, emit: Rc<DispatcherFn>) {
