From 5d8dd6fb630c5bfbb20f383e48e46e332d920e3d Mon Sep 17 00:00:00 2001 From: SinTan1729 Date: Tue, 26 Mar 2024 23:52:24 -0500 Subject: [PATCH] chg: Use Option instead of returning empty String --- actix/src/database.rs | 15 ++++----------- actix/src/main.rs | 7 +++---- actix/src/utils.rs | 6 +++--- 3 files changed, 10 insertions(+), 18 deletions(-) diff --git a/actix/src/database.rs b/actix/src/database.rs index c939c14..53e32e6 100644 --- a/actix/src/database.rs +++ b/actix/src/database.rs @@ -1,20 +1,13 @@ use rusqlite::Connection; -pub fn find_url(shortlink: &str, db: &Connection) -> String { +pub fn find_url(shortlink: &str, db: &Connection) -> Option { let mut statement = db .prepare_cached("SELECT long_url FROM urls WHERE short_url = ?1") .unwrap(); - let links = statement - .query_map([shortlink], |row| row.get("long_url")) - .unwrap(); - - let mut longlink = String::new(); - for link in links { - longlink = link.unwrap(); - } - - longlink + statement + .query_row([shortlink], |row| row.get("long_url")) + .ok() } pub fn getall(db: &Connection) -> Vec { diff --git a/actix/src/main.rs b/actix/src/main.rs index 1c2419c..40cc920 100644 --- a/actix/src/main.rs +++ b/actix/src/main.rs @@ -78,10 +78,7 @@ async fn error404() -> impl Responder { #[get("/{shortlink}")] async fn link_handler(shortlink: web::Path, data: web::Data) -> impl Responder { let shortlink_str = shortlink.to_string(); - let longlink = utils::get_longurl(shortlink_str, &data.db); - if longlink.is_empty() { - Redirect::to("/err/404") - } else { + if let Some(longlink) = utils::get_longurl(shortlink_str, &data.db) { let redirect_method = env::var("redirect_method").unwrap_or(String::from("PERMANENT")); database::add_hit(shortlink.as_str(), &data.db); if redirect_method == "TEMPORARY" { @@ -90,6 +87,8 @@ async fn link_handler(shortlink: web::Path, data: web::Data) - // Defaults to permanent redirection Redirect::to(longlink).permanent() } + } else { + Redirect::to("/err/404") } } diff --git a/actix/src/utils.rs b/actix/src/utils.rs index b474fe5..ba64e66 100644 --- a/actix/src/utils.rs +++ b/actix/src/utils.rs @@ -3,11 +3,11 @@ use rand::seq::SliceRandom; use regex::Regex; use rusqlite::Connection; -pub fn get_longurl(shortlink: String, db: &Connection) -> String { +pub fn get_longurl(shortlink: String, db: &Connection) -> Option { if validate_link(&shortlink) { database::find_url(shortlink.as_str(), db) } else { - String::new() + None } } @@ -35,7 +35,7 @@ pub fn add_link(req: String, db: &Connection) -> (bool, String) { shortlink = random_name(); } - if validate_link(shortlink.as_str()) && get_longurl(shortlink.clone(), db).is_empty() { + if validate_link(shortlink.as_str()) && get_longurl(shortlink.clone(), db).is_none() { ( database::add_link(shortlink.clone(), longlink, db), shortlink,