70 lines
1.9 KiB
Rust
70 lines
1.9 KiB
Rust
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<SqliteConnectionManager>;
|
|
|
|
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<PooledConnection<SqliteConnectionManager>> {
|
|
self.pool
|
|
.get()
|
|
.map_err(|_e| error::ErrorBadRequest("Cannot get DB connection."))
|
|
}
|
|
|
|
pub fn get_authentication_service<'a>(
|
|
&'a self,
|
|
_conn: &'a PooledConnection<SqliteConnectionManager>,) -> Result<SessionService> {
|
|
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<SqliteConnectionManager>,
|
|
) -> Result<UserService> {
|
|
Ok(UserService::new(conn))
|
|
}
|
|
|
|
pub fn get_security_service<'a>(
|
|
&'a self,
|
|
conn: &'a PooledConnection<SqliteConnectionManager>,
|
|
) -> Result<SecurityService> {
|
|
Ok(SecurityService::new(conn))
|
|
}
|
|
|
|
pub fn get_account_service<'a>(
|
|
&'a self,
|
|
conn: &'a PooledConnection<SqliteConnectionManager>,
|
|
)-> Result<AccountService> {
|
|
Ok(AccountService::new(conn))
|
|
}
|
|
}
|