Skip to content

Commit

Permalink
feat: Add rand crate and update link routes
Browse files Browse the repository at this point in the history
  • Loading branch information
ikurotime committed Dec 29, 2023
1 parent 1ff524a commit 75ee051
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 20 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ tracing = "0.1.40"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
sqlx = { version = "0.6", features = ["postgres", "runtime-tokio-rustls"] }
dotenv = "0.15.0"
rand = "0.8.5"
6 changes: 0 additions & 6 deletions migrations/0001_Create_Links_Table.sql

This file was deleted.

22 changes: 22 additions & 0 deletions migrations/0001_Create_Tables.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
CREATE TABLE "User" (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE,
name VARCHAR(255),
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE "Links" (
id SERIAL PRIMARY KEY,
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
original_url VARCHAR(255),
short_url VARCHAR(255),
userId INTEGER REFERENCES "User"(id) ON DELETE SET NULL
);
CREATE TABLE "QRCodes" (
id SERIAL PRIMARY KEY,
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
qr_code TEXT,
userId INTEGER REFERENCES "User"(id) ON DELETE SET NULL
);
2 changes: 1 addition & 1 deletion src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@ fn router() -> Router {
ServeDir::new(format!("{}/assets", assets_path.to_str().unwrap())),
)
.nest("/api", routes::user_routes::get_routes())
.nest("/link", routes::link_routes::get_routes())
.nest("/api/link", routes::link_routes::get_routes())
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async fn main() -> anyhow::Result<()> {
info!("Initialized router!");
let url = dotenv::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file");

let mut sqlx_connection = PgPoolOptions::new()
let sqlx_connection = PgPoolOptions::new()
.max_connections(250) // TODO: Set this to a reasonable value
.connect(&url)
.await
Expand Down
44 changes: 32 additions & 12 deletions src/routes/link_routes.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use crate::http::ApiContext;
use axum::{http::StatusCode, routing::post, Extension, Form, Router};
use rand;
use rand::Rng;
use serde::Deserialize;
use sqlx::{Error, PgPool};
use tracing::info;

#[derive(sqlx::FromRow, Debug, Deserialize)] // Add this line
struct LinkRequest {
original_url: String,
Expand All @@ -17,19 +19,37 @@ pub fn get_routes() -> Router {
}

async fn add_link(ctx: Extension<ApiContext>, Form(payload): Form<LinkRequest>) -> StatusCode {
//get the link from the form
// Get the link from the form
info!("{:?}", payload.original_url);
info!("{:?}", payload.path);
//store the links in the database
let link = sqlx::query_as::<_, LinkRequest>(
"INSERT INTO links (original_url, path) VALUES ($1, $2) RETURNING link",
)
.bind(payload.original_url)
.bind(payload.path)
.fetch_one(&ctx.db) // Replace sqlx_connection with pool
.await
.unwrap();

//return the link / return text with link and show it in the UI
// Store the links in the database
if let Err(err) = insert_link(&payload, &ctx.db).await {
// Handle the error, log it, and return an appropriate status code
eprintln!("Error inserting link: {}", err);
return StatusCode::INTERNAL_SERVER_ERROR;
}

// Return the link / return text with link and show it in the UI
StatusCode::OK
}
async fn insert_link(payload: &LinkRequest, pool: &PgPool) -> Result<(), Error> {
let path = if payload.path.is_empty() {
generate_random_string(5)
} else {
payload.path.clone()
};

let _insertion =
sqlx::query("INSERT INTO \"Links\" (original_url, short_url) VALUES ($1, $2);")
.bind(&payload.original_url)
.bind(&path)
.execute(pool)
.await?;

Ok(())
}
fn generate_random_string(length: usize) -> String {
let mut rng = rand::thread_rng();
(0..length).map(|_| rng.gen_range('a'..='z')).collect()
}

0 comments on commit 75ee051

Please sign in to comment.