use sqlx::PgPool; use crate::core::*; use crate::data::{MemAccountDataSource, PgAccountDataSource}; use crate::model::{Account, AccountId, NewAccount}; pub struct AccountRepo { db: PgAccountDataSource, mem: MemAccountDataSource, } impl AccountRepo { pub fn new(db_pool: PgPool) -> AccountRepo { AccountRepo { db: PgAccountDataSource::new(db_pool), mem: MemAccountDataSource::new(), } } pub async fn by_id(&self, id: I) -> Result where I: Into + Send, { let id = id.into(); match self.mem.by_id(id).await { Some(account) => Ok(account), None => self.db.by_id(id).await, } } pub async fn create(&self, new: T) -> Result where T: TryInto, Error = E> + Send, E: Into, { let new = new.try_into().map_err(|e| e.into())?.inner(); let account = self.db.create(new).await?; self.mem.store(account.clone()).await; Ok(account) } pub async fn delete(&self, id: I) -> Result<()> where I: Into + Send, { let id = id.into(); self.db.delete(id).await?; self.mem.delete(id).await; Ok(()) } }