Add few comments

This commit is contained in:
gabatxo1312 2026-01-29 16:52:35 +01:00
parent 673fd2c58a
commit 374d318dea
No known key found for this signature in database
2 changed files with 24 additions and 2 deletions

View File

@ -40,24 +40,29 @@ impl ActiveModelBehavior for ActiveModel {}
#[derive(Debug, Snafu)] #[derive(Debug, Snafu)]
#[snafu(visibility(pub))] #[snafu(visibility(pub))]
pub enum BookError { pub enum BookError {
// #[snafu(display("The Content Folder (Path: {path}) does not exist"))] /// Db Error from SeaOrm
// NotFound { path: String },
#[snafu(display("Database error"))] #[snafu(display("Database error"))]
DB { source: sea_orm::DbErr }, DB { source: sea_orm::DbErr },
/// When Book with Id is not found
#[snafu(display("Book with id {id} not found"))] #[snafu(display("Book with id {id} not found"))]
NotFound { id: i32 }, NotFound { id: i32 },
} }
#[derive(Debug)] #[derive(Debug)]
/// Operator for the CRUD on Book Model
pub struct BookOperator { pub struct BookOperator {
pub state: AppState, pub state: AppState,
} }
impl BookOperator { impl BookOperator {
/// Creates a new `BookOperator` with the given application state.
pub fn new(state: AppState) -> Self { pub fn new(state: AppState) -> Self {
Self { state } Self { state }
} }
/// Lists all books matching the optional query filters.
///
/// Results are ordered by ID in descending order (newest first).
pub async fn list(&self, query: Option<BookQuery>) -> Result<Vec<Model>, BookError> { pub async fn list(&self, query: Option<BookQuery>) -> Result<Vec<Model>, BookError> {
let mut conditions = Condition::all(); let mut conditions = Condition::all();
if let Some(book_query) = query { if let Some(book_query) = query {
@ -86,6 +91,10 @@ impl BookOperator {
.context(DBSnafu) .context(DBSnafu)
} }
/// Finds a book by its ID.
///
/// # Errors
/// Returns `BookError::NotFound` if no book exists with the given ID.
pub async fn find_by_id(&self, id: i32) -> Result<Model, BookError> { pub async fn find_by_id(&self, id: i32) -> Result<Model, BookError> {
let book_by_id = Entity::find_by_id(id) let book_by_id = Entity::find_by_id(id)
.one(&self.state.db) .one(&self.state.db)
@ -99,6 +108,7 @@ impl BookOperator {
} }
} }
/// Creates a new book from the given form data.
pub async fn create(&self, form: BookForm) -> Result<Model, BookError> { pub async fn create(&self, form: BookForm) -> Result<Model, BookError> {
let book = ActiveModel { let book = ActiveModel {
title: Set(form.title.clone()), title: Set(form.title.clone()),
@ -113,6 +123,10 @@ impl BookOperator {
book.insert(&self.state.db).await.context(DBSnafu) book.insert(&self.state.db).await.context(DBSnafu)
} }
/// Update a book (find with ID) from the given form data
///
/// # Error
/// Returns BookError::NotFound if id is not found in database
pub async fn update(&self, id: i32, form: BookForm) -> Result<Model, BookError> { pub async fn update(&self, id: i32, form: BookForm) -> Result<Model, BookError> {
let book_by_id = Self::find_by_id(&self, id).await.context(BookSnafu); let book_by_id = Self::find_by_id(&self, id).await.context(BookSnafu);
@ -132,6 +146,7 @@ impl BookOperator {
} }
} }
/// Delete a book (find with ID)
pub async fn delete(&self, id: i32) -> Result<DeleteResult, BookError> { pub async fn delete(&self, id: i32) -> Result<DeleteResult, BookError> {
let book: Option<Model> = Entity::find_by_id(id) let book: Option<Model> = Entity::find_by_id(id)
.one(&self.state.db) .one(&self.state.db)

View File

@ -29,6 +29,7 @@ struct BookWithUser {
pub current_holder: Option<UserModel>, pub current_holder: Option<UserModel>,
} }
/// Query for filter search query
#[serde_as] #[serde_as]
#[derive(Deserialize, Clone)] #[derive(Deserialize, Clone)]
pub struct BookQuery { pub struct BookQuery {
@ -52,21 +53,26 @@ pub async fn index(
State(state): State<AppState>, State(state): State<AppState>,
Query(query): Query<BookQuery>, Query(query): Query<BookQuery>,
) -> Result<impl axum::response::IntoResponse, AppStateError> { ) -> Result<impl axum::response::IntoResponse, AppStateError> {
// Get all Users
let users = UserOperator::new(state.clone()) let users = UserOperator::new(state.clone())
.list() .list()
.await .await
.context(UserSnafu)?; .context(UserSnafu)?;
// Get all Book filtered with query
let books = BookOperator::new(state) let books = BookOperator::new(state)
.list(Some(query.clone())) .list(Some(query.clone()))
.await .await
.context(BookSnafu)?; .context(BookSnafu)?;
// Mapping between an user_id and user used in result to
// get easily user with his id
let user_by_id: HashMap<i32, UserModel> = users let user_by_id: HashMap<i32, UserModel> = users
.clone() .clone()
.into_iter() .into_iter()
.map(|user| (user.id, user)) .map(|user| (user.id, user))
.collect(); .collect();
// Build object of Book with his relation Owner (User) and current_holder (User)
let result: Vec<BookWithUser> = books let result: Vec<BookWithUser> = books
.into_iter() .into_iter()
.filter_map(|book| { .filter_map(|book| {
@ -131,6 +137,7 @@ pub async fn show(
}) })
} }
/// Form to build a new book or an update
#[serde_as] #[serde_as]
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct BookForm { pub struct BookForm {