Skip to content
This repository has been archived by the owner on Jun 18, 2024. It is now read-only.

Commit

Permalink
Use shortener generator for POST endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianEffe committed Aug 13, 2023
1 parent e768beb commit 61ac253
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 17 deletions.
4 changes: 2 additions & 2 deletions src/key_generator.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use base62::encode;
use md5::compute;

pub fn generate(url: &str) -> String {
let hash = compute(url);
pub fn generate(value: &str) -> String {
let hash = compute(value);
let hash_bytes: [u8; 16] = hash.into();
let hash_u128: u128 = u128::from_le_bytes(hash_bytes);
encode(hash_u128)[..7].to_string()
Expand Down
52 changes: 37 additions & 15 deletions src/routes/full_url.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,52 @@
use crate::{model::UrlRequestModel, schema::CreateShortUrlSchema, AppState};
use crate::{
key_generator::generate, model::UrlRequestModel, schema::CreateShortUrlSchema, AppState,
};
use axum::{extract::State, Json};
use chrono::Utc;
use sqlx::Error;
use std::sync::Arc;
use uuid::Uuid;

pub async fn full_url(
State(data): State<Arc<AppState>>,
Json(payload): Json<CreateShortUrlSchema>,
) {
let query_result = sqlx::query_as!(
let mut retry_count = 3;

while retry_count > 0 {
let query_result = insert_in_db(&payload.url, State(data.clone())).await;

match query_result {
Ok(note) => {
println!("okay received testing: {:?}", note);
break;
}
Err(e) => {
println!("failed with error: {:?}", e);
//TODO : - For now assume is failing because of error code 23505, that stands for
//duplicate key
retry_count += 1;
}
}
}
}

async fn insert_in_db(
url: &str,
State(data): State<Arc<AppState>>,
) -> Result<UrlRequestModel, Error> {
let uuid = Uuid::new_v4();
let modifier = uuid.to_string() + url;
let shortened = generate(&modifier);

sqlx::query_as!(
UrlRequestModel,
"INSERT INTO briefly (id, url, extension, created_at) VALUES ($1, $2, $3, $4) RETURNING *",
Uuid::new_v4(),
payload.url.to_string(),
Uuid::new_v4().to_string(), // TODO: - handle extension to be shortened url extension
uuid,
url.to_string(),
shortened,
Utc::now()
)
.fetch_one(&data.db)
.await;

match query_result {
Ok(note) => {
println!("okay received testing: {:?}", note);
}
Err(e) => {
println!("{:?}", e);
}
}
.await
}

0 comments on commit 61ac253

Please sign in to comment.