chg: Use Option instead of returning empty String

This commit is contained in:
SinTan1729 2024-03-26 23:52:24 -05:00
parent 5e4db14ea2
commit 5d8dd6fb63
No known key found for this signature in database
GPG Key ID: EB3E68BFBA25C85F
3 changed files with 10 additions and 18 deletions

View File

@ -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<String> {
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<String> {

View File

@ -78,10 +78,7 @@ async fn error404() -> impl Responder {
#[get("/{shortlink}")]
async fn link_handler(shortlink: web::Path<String>, data: web::Data<AppState>) -> 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<String>, data: web::Data<AppState>) -
// Defaults to permanent redirection
Redirect::to(longlink).permanent()
}
} else {
Redirect::to("/err/404")
}
}

View File

@ -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<String> {
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,