Skip to content

Commit

Permalink
feat: redirection count
Browse files Browse the repository at this point in the history
  • Loading branch information
angeloanan committed Aug 7, 2024
1 parent 2c1287d commit c1c0226
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/db.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fs;

use libsql::Builder;
use tracing::{debug, info, instrument};
use tracing::{debug, instrument};

const DB_PATH: &str = "data/links.db";

Expand Down Expand Up @@ -50,6 +50,17 @@ async fn migrate(conn: libsql::Connection) {
version = 1;
}

if version == 1 {
debug!("Migrating from version 1 -> 2");
conn.execute(
"ALTER TABLE links ADD COLUMN visitor_count INTEGER DEFAULT 0",
(),
)
.await
.expect("Unable to add visitor_count column");
version = 2;
}

conn.execute(&format!("PRAGMA user_version = {version}"), ())
.await
.expect("Unable to set user_version");
Expand Down
11 changes: 10 additions & 1 deletion src/routes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,11 @@ pub async fn handle_short_url(
}

let conn = state.db.clone();
let short_url = uri.to_lowercase();
let mut target_url_query_rows = conn
.query(
"SELECT target_url FROM links WHERE short_url = ?",
[uri.to_lowercase().as_str()],
[short_url.clone()],
)
.await
.expect("Unable to execute query");
Expand All @@ -86,6 +87,14 @@ pub async fn handle_short_url(
if let Some(row) = target_url_query_rows.next().await.unwrap() {
let target_url = row.get::<String>(0).expect("Unable to get target_url");
info!("[{ip:?}] Redirecting {uri} to {target_url}");

conn.execute(
"UPDATE OR IGNORE links SET visitor_count = visitor_count + 1 WHERE short_url = ?;",
[short_url.clone()],
)
.await
.ok();

axum::response::Redirect::to(&target_url).into_response()
} else {
info!("[{ip:?}] Visited {uri}");
Expand Down

0 comments on commit c1c0226

Please sign in to comment.