This repository has been archived by the owner on Jun 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use shortener generator for POST endpoint
- Loading branch information
1 parent
e768beb
commit 61ac253
Showing
2 changed files
with
39 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |