mirror of
https://github.com/SinTan1729/chhoto-url
synced 2025-04-28 11:56:52 -05:00
chg: Properly validate error types
This commit is contained in:
parent
21f76f2962
commit
c23fcdc9bd
2 changed files with 12 additions and 7 deletions
|
@ -1,7 +1,7 @@
|
|||
// SPDX-FileCopyrightText: 2023 Sayantan Santra <sayantan.santra689@gmail.com>
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use rusqlite::Connection;
|
||||
use rusqlite::{Connection, Error};
|
||||
use serde::Serialize;
|
||||
|
||||
// Struct for encoding a DB row
|
||||
|
@ -67,12 +67,11 @@ pub fn add_hit(shortlink: &str, db: &Connection) {
|
|||
}
|
||||
|
||||
// Insert a new link
|
||||
pub fn add_link(shortlink: String, longlink: String, db: &Connection) -> bool {
|
||||
pub fn add_link(shortlink: String, longlink: String, db: &Connection) -> Result<usize, Error> {
|
||||
db.execute(
|
||||
"INSERT INTO urls (long_url, short_url, hits) VALUES (?1, ?2, ?3)",
|
||||
(longlink, shortlink, 0),
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
// Delete and existing link
|
||||
|
|
|
@ -128,10 +128,16 @@ pub fn add_link(req: String, db: &Connection) -> (bool, String) {
|
|||
}
|
||||
|
||||
if validate_link(chunks.shortlink.as_str()) {
|
||||
if database::add_link(chunks.shortlink.clone(), chunks.longlink, db) {
|
||||
(true, chunks.shortlink)
|
||||
} else {
|
||||
(false, String::from("Short URL is already in use!"))
|
||||
match database::add_link(chunks.shortlink.clone(), chunks.longlink, db) {
|
||||
Ok(_) => (true, chunks.shortlink),
|
||||
Err(error) => {
|
||||
if error.to_string() == "UNIQUE constraint failed: urls.short_url" {
|
||||
(false, String::from("Short URL is already in use!"))
|
||||
} else {
|
||||
// This should be super rare
|
||||
(false, String::from("Something went wrong!"))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(false, String::from("Short URL is not valid!"))
|
||||
|
|
Loading…
Reference in a new issue