Skip to content

Commit

Permalink
api works
Browse files Browse the repository at this point in the history
  • Loading branch information
Joeyh021 committed May 17, 2023
1 parent b8cd1c7 commit 5126c0b
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 14 deletions.
27 changes: 27 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,7 @@ sqlx = { version = "0.6.3", features = [
"chrono",
] }
tokio = { version = "1.28.1", features = ["macros", "rt-multi-thread"] }
tower = "0.4.13"
tower-http = { version = "0.4.0", features = ["catch-panic"] }
tracing = "0.1.37"
tracing-subscriber = "0.3.17"
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
group_imports = "StdExternalCrate"
imports_granularity = "Crate"
reorder_imports = true
12 changes: 12 additions & 0 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,15 @@ pub async fn bump_count(source: &str, conn: &PgPool) -> Result<(), sqlx::Error>
.await
.map(|_| ())
}

///adds a new go link to the database
pub async fn add_new(source: &str, sink: &str, conn: &PgPool) -> Result<(), sqlx::Error> {
sqlx::query!(
"INSERT INTO redirects (source, sink) VALUES ($1, $2)",
source,
sink
)
.execute(conn)
.await
.map(|_| ())
}
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ async fn main() -> anyhow::Result<()> {
.route("/:source", get(routes::do_redirect))
.nest("/api", routes::api_routes(api_secret))
.with_state(state)
.fallback(|| async { (StatusCode::NOT_FOUND, "Not Found") });
.fallback(|| async { (StatusCode::NOT_FOUND, "Not Found") })
.layer(tower_http::catch_panic::CatchPanicLayer::new());

tracing::info!("Starting server...");
axum::Server::bind(&([0, 0, 0, 0], port).into())
Expand Down
47 changes: 34 additions & 13 deletions src/routes/api.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::todo;
use std::collections::HashMap;

use crate::AppState;

Expand All @@ -10,29 +10,50 @@ use axum::{
routing::{get, post},
Json, Router,
};
use sqlx::{error::DatabaseError, postgres::PgDatabaseError, Database};

use crate::db;

#[derive(Debug, serde::Deserialize)]
struct GoPair {
source: String,
sink: String,
}

#[tracing::instrument]
pub async fn add_redirect(
async fn add_redirect(
State(AppState { pool, config: _ }): State<AppState>,
) -> impl IntoResponse {
todo!()
Json(GoPair { source, sink }): Json<GoPair>,
) -> Result<StatusCode> {
let r = db::add_new(&source, &sink, &pool).await;
match r {
Ok(_) => Ok(StatusCode::CREATED),
Err(sqlx::Error::Database(e)) if e.code() == Some("23505".into()) => {
tracing::warn!("API request attempted to insert duplicate go link {source} -> {sink}");
Ok(StatusCode::CONFLICT)
}
Err(e) => {
tracing::error!("Failed to handle API request: {e:?}");
Err(StatusCode::INTERNAL_SERVER_ERROR.into())
}
}
}

pub async fn get_redirects(
#[tracing::instrument]
async fn get_redirects(
State(AppState { pool, config: _ }): State<AppState>,
Query(q): Query<Option<usize>>,
Query(q): Query<HashMap<String, i64>>,
) -> Result<Json<Vec<crate::Redirect>>> {
match q {
Some(n) => db::get_recent(&pool, n as i64).await,
match match q.get("n") {
Some(n) => db::get_recent(&pool, *n).await,
None => db::get_all(&pool).await,
} {
Ok(r) => Ok(Json(r)),
Err(e) => {
tracing::error!("Failed to handle API request: {e}");
Err(StatusCode::INTERNAL_SERVER_ERROR.into())
}
}
.map(axum::Json)
.map_err(|e| {
tracing::error!("Failed to handle API request: {e}");
StatusCode::INTERNAL_SERVER_ERROR.into()
})
}

pub fn api_routes(tok: &'static str) -> Router<AppState> {
Expand Down

0 comments on commit 5126c0b

Please sign in to comment.