diff options
| -rw-r--r-- | src/app/store/mod.rs | 73 |
1 files changed, 68 insertions, 5 deletions
diff --git a/src/app/store/mod.rs b/src/app/store/mod.rs index 70df5c2..cd4b859 100644 --- a/src/app/store/mod.rs +++ b/src/app/store/mod.rs @@ -44,6 +44,7 @@ impl Default for AppContext { fn default() -> Self { AppContext { context: Context::default(), + // these defaults get overwritten when #init_context is run accounts: vec![], symbols: vec![], events: vec![], @@ -62,17 +63,79 @@ pub trait Store { } impl AppContext { - pub fn unwrap_store(&mut self) -> &mut impl Store { - match &mut self.context { - Context::SQLite(store) => store, - } + /// Returns a mutable version of the generic implementation of the store + /// along with references to the objects in context. Both store and context + /// need to be updated in tandem, so a tuple must be returned to be able to + /// produce mutable references in the same lifetime + fn unwrap_store( + &mut self, + ) -> ( + &mut impl Store, + &mut Vec<FiduciaryAccount>, + &mut Vec<EquitySymbol>, + &mut Vec<EquityChangeEvent>, + ) { + ( + match &mut self.context { + Context::SQLite(store) => store, + }, + &mut self.accounts, + &mut self.symbols, + &mut self.events, + ) } - pub fn get_store(&self) -> &impl Store { + fn get_store(&self) -> &impl Store { match &self.context { Context::SQLite(store) => store, } } + + pub fn init_context(&mut self) -> Result<(), ContextError> { + self.unwrap_store().0.init()?; + + self.accounts = self.get_store().get_accounts()?; + self.symbols = self.get_store().get_symbols()?; + self.events = self.get_store().get_events()?; + + Ok(()) + } + + pub fn get_accounts(&self) -> &Vec<FiduciaryAccount> { + &self.accounts + } + + pub fn get_symbols(&self) -> &Vec<EquitySymbol> { + &self.symbols + } + + pub fn get_events(&self) -> &Vec<EquityChangeEvent> { + &self.events + } + + pub fn add_account(&mut self, account: FiduciaryAccount) -> Result<(), ContextError> { + let (store, accounts, ..) = self.unwrap_store(); + let acc = accounts.push_mut(account); + + store.add_account(acc)?; + Ok(()) + } + + pub fn add_symbol(&mut self, symbol: EquitySymbol) -> Result<(), ContextError> { + let (store, _, symbols, ..) = self.unwrap_store(); + let sym = symbols.push_mut(symbol); + + store.add_symbol(sym)?; + Ok(()) + } + + pub fn add_event(&mut self, event: EquityChangeEvent) -> Result<(), ContextError> { + let (store, .., events) = self.unwrap_store(); + let ev = events.push_mut(event); + + store.add_event(ev)?; + Ok(()) + } } #[cfg(test)] |
