59 lines
1.6 KiB
Rust
59 lines
1.6 KiB
Rust
use crate::services::{SecurityService, SessionService, UserService};
|
|
|
|
use actix_web::{error, Result};
|
|
use r2d2::PooledConnection;
|
|
use r2d2_sqlite::SqliteConnectionManager;
|
|
|
|
use std::path::PathBuf;
|
|
|
|
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: SessionService,
|
|
}
|
|
|
|
#[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 = SessionService::from_conn(&mut conn).unwrap();
|
|
let cache = ServicesCache { session_service };
|
|
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(&self) -> Result<SessionService> {
|
|
Ok(self.cache.session_service.clone())
|
|
}
|
|
|
|
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))
|
|
}
|
|
}
|