use crate::services::{SecurityService, SessionService, UserService, AccountService}; use actix_web::{error, Error, Result}; use r2d2::PooledConnection; use r2d2_sqlite::SqliteConnectionManager; use std::path::PathBuf; use cookie::Key; pub type DbPool = r2d2::Pool; pub fn creat_db_pool(path: &PathBuf) -> DbPool { let manager = SqliteConnectionManager::file(path); r2d2::Pool::new(manager).unwrap() } #[derive(Clone)] struct ServicesCache { session_service_key: Key, } #[derive(Clone)] pub struct ServicesFactory { pool: DbPool, cache: ServicesCache, } impl ServicesFactory { pub fn new(pool: DbPool) -> ServicesFactory { let mut conn = pool.get().unwrap(); let session_service_key = SessionService::get_key(&mut conn).unwrap(); let cache = ServicesCache { session_service_key }; ServicesFactory { pool, cache } } pub fn get_connection(&self) -> Result> { self.pool .get() .map_err(|_e| error::ErrorBadRequest("Cannot get DB connection.")) } pub fn get_authentication_service<'a>( &'a self, _conn: &'a PooledConnection,) -> Result { let user_service = self.get_user_service(_conn)?; Ok(SessionService::create(& self.cache.session_service_key, user_service)) } pub fn get_user_service<'a>( &'a self, conn: &'a PooledConnection, ) -> Result { Ok(UserService::new(conn)) } pub fn get_security_service<'a>( &'a self, conn: &'a PooledConnection, ) -> Result { Ok(SecurityService::new(conn)) } pub fn get_account_service<'a>( &'a self, conn: &'a PooledConnection, )-> Result { Ok(AccountService::new(conn)) } }