From e5b28029c920610020175ba48f067275a3bcdba2 Mon Sep 17 00:00:00 2001 From: "flyingscorpio@clevo" Date: Fri, 6 Jan 2023 17:31:31 +0100 Subject: [PATCH] Return Title when inserting favorite --- src/database.rs | 16 +++++++++------- src/ear.rs | 2 +- src/models.rs | 2 +- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/database.rs b/src/database.rs index 86e45ac..0b8b798 100644 --- a/src/database.rs +++ b/src/database.rs @@ -35,20 +35,22 @@ pub fn add_all_titles<'a>( } /// Inserts a favorite in the local database, if a matching Title exists. -pub fn insert_favorite(title_mirabelid: i32) -> Result<(), DatabaseError> { +/// Returns the matching Title if successful, otherwise an error. +pub fn insert_favorite(title_mirabelid: i32) -> Result { let connection = &mut crud::establish_connection()?; - // search for a matching title - if crud::search_title_from_mirabelid(connection, title_mirabelid)?.is_empty() { - // no matching title, return an error - Err(DatabaseError::NotFound) + // search for a matching title, and return error if not found + let matching_title = crud::search_title_from_mirabelid(connection, title_mirabelid)?; + + if matching_title.is_empty() { + return Err(DatabaseError::NotFound); } else { // title exists: check if the favorite already exists and insert it if crud::search_favorite_from_mirabelid(connection, title_mirabelid)?.is_empty() { // no favorite found, insert it let new_favorite = InsertFavorite { title_mirabelid }; - crud::create_favorite(connection, new_favorite); - Ok(()) + crud::create_favorite(connection, new_favorite)?; + return Ok(matching_title[0].clone()); } else { // else return an error Err(DatabaseError::FoundDuplicate) diff --git a/src/ear.rs b/src/ear.rs index 8de1473..b980409 100644 --- a/src/ear.rs +++ b/src/ear.rs @@ -129,7 +129,7 @@ fn handle_request(request: Request, mut sender: Mouth) { }, }; match database::insert_favorite(mirabelid) { - Ok(result) => sender.send_data(Status::OK, serde_json::json!(result)), + Ok(result) => sender.send_data(Status::OK, serde_json::json!(format!("Favori inséré avec succès : {}", result.titre))), Err(err) => match err { database::DatabaseError::NotFound => sender.send_data(Status::NotFound, serde_json::json!(format!("{}", err))), database::DatabaseError::FoundDuplicate => sender.send_data(Status::BadRequest, serde_json::json!(format!("{}", err))), diff --git a/src/models.rs b/src/models.rs index c7496a7..8cd5985 100644 --- a/src/models.rs +++ b/src/models.rs @@ -21,7 +21,7 @@ pub struct InsertFavorite { } /// Title struct, mapped to the SQL title table. -#[derive(Queryable, Debug, Serialize)] +#[derive(Queryable, Debug, Serialize, Clone)] pub struct Title { pub id: i32, pub mirabelid: i32,