Refactoring

This commit is contained in:
2025-09-09 07:39:16 +03:00
parent e7713f3529
commit c86be31d54
7 changed files with 87 additions and 39 deletions

View File

@@ -1,34 +1,45 @@
use crate::application::config::{Config, Storage};
use crate::application::services::books::Books; use crate::application::services::books::Books;
use crate::application::config::Config;
use crate::domain::book::Book; use crate::domain::book::Book;
use crate::domain::repository::{BookFilter, Repository}; use crate::domain::repository::{BookFilter, Repository};
use crate::infrastructure::repository::inmem;
use std::sync::{Arc, Mutex};
pub struct Application<R: Repository<Book, BookFilter>> { pub struct Application {
pub books: Books<R>,
cfg: Config, cfg: Config,
pub repo: Arc<Mutex<Box<dyn Repository<Book, BookFilter> + 'static>>>,
pub srv: Books,
} }
impl<R: Repository<Book, BookFilter> +'static> Application<R> { impl Application {
pub fn new(repo: R) -> Self { pub fn new() -> Self {
let cfg = Config::new(); let cfg = Config::new();
Application { let repo: Box<dyn Repository<Book, BookFilter>> = match cfg.storage {
books: Books::new(repo, (&cfg.books_dir).into(), "https://foo.bar/".to_string()), Storage::InMemory => Box::new(inmem::books::BookRepository::new()),
};
let repo = Arc::new(Mutex::new(repo));
let srv = Books::new(
repo.clone(),
cfg.books_dir.clone().into(),
"https://foo.bar".to_string(),
);
cfg Application {
cfg,
repo,
srv
} }
} }
pub fn start(&mut self) -> Result<(), String>{ pub fn start(&mut self) -> Result<(), String> {
self.books.add_books_from_path(); self.srv.add_books_from_path();
if self.cfg.watcher { if self.cfg.watcher {
return match self.books.watch_dir() { return match self.srv.watch_dir() {
Ok(_) => {Ok(())} Ok(_) => Ok(()),
Err(e) => { Err(e) => Err(format!("Error start watching books: {}", e)),
Err(format!("Error start watching books: {}", e)) };
}
}
} }
Ok(()) Ok(())

View File

@@ -1,4 +1,7 @@
use envman::EnvMan; use envman::EnvMan;
use std::error::Error;
use std::fmt;
use std::str::FromStr;
#[derive(EnvMan)] #[derive(EnvMan)]
pub struct Config { pub struct Config {
@@ -6,6 +9,8 @@ pub struct Config {
pub books_dir: String, pub books_dir: String,
#[envman(default = "true")] #[envman(default = "true")]
pub watcher: bool, pub watcher: bool,
#[envman(default = "inmemory")]
pub storage: Storage,
} }
impl Config { impl Config {
@@ -13,3 +18,31 @@ impl Config {
Config::load_from_env().expect("Failed to load configuration") Config::load_from_env().expect("Failed to load configuration")
} }
} }
pub enum Storage {
InMemory,
}
#[derive(Debug)]
pub struct ParseStorageError {
details: String,
}
impl fmt::Display for ParseStorageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Unknown storage type: {}", self.details)
}
}
impl Error for ParseStorageError {}
impl FromStr for Storage {
type Err = ParseStorageError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"inmemory" => Ok(Storage::InMemory),
_ => Err(ParseStorageError { details: s.into() }),
}
}
}

View File

@@ -10,19 +10,20 @@ use url::Url;
const AUTHOR_URL_PREFIX: &str = "author"; const AUTHOR_URL_PREFIX: &str = "author";
pub struct Books<R: Repository<Book, BookFilter>> { pub struct Books {
pub repo: Arc<Mutex<R>>, pub repo: Arc<Mutex<Box<dyn Repository<Book, BookFilter> + 'static>>>,
root: PathBuf, root: PathBuf,
base_url: Url, base_url: Url,
} }
impl<R: Repository<Book, BookFilter>> Books<R> impl Books {
where pub fn new(
R: 'static, repo: Arc<Mutex<Box<dyn Repository<Book, BookFilter> + 'static>>>,
{ root: PathBuf,
pub fn new(repo: R, root: PathBuf, base_url: String) -> Self { base_url: String,
) -> Self {
Books { Books {
repo: Arc::new(Mutex::new(repo)), repo,
root, root,
base_url: Url::parse(&base_url).unwrap(), base_url: Url::parse(&base_url).unwrap(),
} }
@@ -68,7 +69,15 @@ where
pub fn add_books_from_path(&mut self) { pub fn add_books_from_path(&mut self) {
let iter = fs::Loader::new(PathBuf::from(&self.root)); let iter = fs::Loader::new(PathBuf::from(&self.root));
self.repo.lock().unwrap().bulk_add(iter);
match self.repo.lock() {
Ok(mut repo) => {
for book in iter {
repo.add(book);
}
}
Err(err) => eprintln!("{}", err),
}
} }
pub fn watch_dir(&mut self) -> Result<(), io::Error> { pub fn watch_dir(&mut self) -> Result<(), io::Error> {

View File

@@ -1,10 +1,10 @@
pub trait Repository<T, F>: Send + Sync + Sized{ pub trait Repository<T, F>: Send + Sync {
fn add(&mut self, item: T); fn add(&mut self, item: T);
fn bulk_add<I>(&mut self, items: I) where I: IntoIterator<Item = T>; fn bulk_add(&mut self, items: Vec<T>);
fn remove(&mut self, item: T); fn remove(&mut self, item: T);
fn get(&self, id: String) -> Option<T>; fn get(&self, id: String) -> Option<T>;
fn update(&mut self, item: T); fn update(&mut self, item: T);
fn filter(&self, filter: F) -> Box<dyn Iterator<Item = T>>; fn filter(&self, filter: F) -> Box<dyn Iterator<Item = T> + '_>;
} }
pub struct BookFilter { pub struct BookFilter {

View File

@@ -1,4 +1,3 @@
use crate::domain::author::Author;
use crate::domain::repository::{BookFilter, Repository}; use crate::domain::repository::{BookFilter, Repository};
use crate::domain::{author, book}; use crate::domain::{author, book};
use std::collections::HashMap; use std::collections::HashMap;
@@ -61,7 +60,7 @@ impl Into<book::Book> for Book {
pub struct BookRepository { pub struct BookRepository {
books: Vec<Book>, books: Vec<Book>,
authors: HashMap<Uuid, Author>, authors: HashMap<Uuid, author::Author>,
author_uniques: HashMap<String, Uuid>, author_uniques: HashMap<String, Uuid>,
} }
@@ -110,10 +109,7 @@ impl Repository<book::Book, BookFilter> for BookRepository {
self.books.push(item.into()); self.books.push(item.into());
} }
fn bulk_add<I>(&mut self, items: I) fn bulk_add(&mut self, items: Vec<book::Book>) {
where
I: IntoIterator<Item = book::Book>,
{
items.into_iter().for_each(|item| { items.into_iter().for_each(|item| {
if self.get(item.id.to_string()).is_none() { if self.get(item.id.to_string()).is_none() {
self.add(item) self.add(item)

View File

@@ -1,13 +1,12 @@
use crate::application::application::Application; use crate::application::application::Application;
use crate::infrastructure::repository::inmem::books::BookRepository;
pub mod domain; pub mod domain;
mod application; mod application;
pub mod infrastructure; pub mod infrastructure;
pub fn demo() -> Application<BookRepository> { pub fn demo() -> Application {
let mut app = Application::new(BookRepository::new()); let mut app = Application::new();
app.start().expect("Application initialization failed"); app.start().expect("Application initialization failed");
app app

View File

@@ -22,11 +22,11 @@ fn main() {
updated: None, updated: None,
}; };
let res = app.books.books_feed(filter); let res = app.srv.books_feed(filter);
println!("{}", to_xml_string(&res).unwrap()); println!("{}", to_xml_string(&res).unwrap());
if let Some(book) = res.entry.iter().next() { if let Some(book) = res.entry.iter().next() {
let book = app.books.repo.lock().unwrap().get(book.id.to_string().clone()); let book = app.repo.lock().unwrap().get(book.id.to_string().clone());
println!("{:?}", book.unwrap().author); println!("{:?}", book.unwrap().author);
} }