summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/errors.rs10
-rw-r--r--src/handlers/ships.rs75
-rw-r--r--src/main.rs36
3 files changed, 76 insertions, 45 deletions
diff --git a/src/errors.rs b/src/errors.rs
index d4b365f..6b3195f 100644
--- a/src/errors.rs
+++ b/src/errors.rs
@@ -1,4 +1,7 @@
-use axum::{response::{Response, IntoResponse}, body::{boxed, self}};
+use axum::{
+ body::{self, boxed},
+ response::{IntoResponse, Response},
+};
use hyper::StatusCode;
use thiserror::Error;
@@ -34,9 +37,6 @@ impl IntoResponse for ServiceError {
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
- Response::builder()
- .status(status)
- .body(body)
- .unwrap()
+ Response::builder().status(status).body(body).unwrap()
}
}
diff --git a/src/handlers/ships.rs b/src/handlers/ships.rs
index 9d985ea..91944fc 100644
--- a/src/handlers/ships.rs
+++ b/src/handlers/ships.rs
@@ -1,56 +1,87 @@
use std::sync::Arc;
-use axum::{Json, extract::Path, Extension};
-use hyper::StatusCode;
-use solarlib::ship::{Ship, DbShip, Sha256};
-use sqlx::{query_as, query, Error as SqlxError};
+use axum::{extract::Path, Extension, Json};
use axum_auth::AuthBearer;
+use hyper::StatusCode;
+use solarlib::ship::{DbShip, Sha256, Ship};
+use sqlx::{query, query_as, Error as SqlxError};
use tracing::log::warn;
-use crate::{errors::{JsonResult, StringResult, ServiceError}, State};
-
+use crate::{
+ errors::{JsonResult, ServiceError, StringResult},
+ State,
+};
pub async fn list(state: Extension<Arc<State>>) -> JsonResult<Json<Vec<Ship>>> {
let mut conn = state.conn.acquire().await?;
- let db_ships = query_as!(DbShip, "SELECT * FROM ships").fetch_all(&mut conn).await?;
+ let db_ships = query_as!(DbShip, "SELECT * FROM ships")
+ .fetch_all(&mut conn)
+ .await?;
- let ships = db_ships.into_iter().map(|d| d.into()).collect::<Vec<Ship>>();
+ let ships = db_ships
+ .into_iter()
+ .map(|d| d.into())
+ .collect::<Vec<Ship>>();
Ok(Json(ships))
}
-pub async fn new(Json(new_ship): Json<Ship>, state: Extension<Arc<State>>, AuthBearer(token): AuthBearer) -> StringResult {
+pub async fn new(
+ Json(new_ship): Json<Ship>,
+ state: Extension<Arc<State>>,
+ AuthBearer(token): AuthBearer,
+) -> StringResult {
check_bearer(token)?;
let mut conn = state.conn.acquire().await?;
- query!("INSERT INTO ships (name, shasum, download_url, version) VALUES ($1, $2, $3, $4)", new_ship.name, new_ship.shasum.to_string(), new_ship.download_url, new_ship.version).execute(&mut conn).await?;
+ query!(
+ "INSERT INTO ships (name, shasum, download_url, version) VALUES ($1, $2, $3, $4)",
+ new_ship.name,
+ new_ship.shasum.to_string(),
+ new_ship.download_url,
+ new_ship.version
+ )
+ .execute(&mut conn)
+ .await?;
Ok("OK")
}
-pub async fn delete(Path(shasum): Path<Sha256>, state: Extension<Arc<State>>, AuthBearer(token): AuthBearer) -> StringResult {
+pub async fn delete(
+ Path(shasum): Path<Sha256>,
+ state: Extension<Arc<State>>,
+ AuthBearer(token): AuthBearer,
+) -> StringResult {
check_bearer(token)?;
let mut conn = state.conn.acquire().await?;
- query!("DELETE FROM ships WHERE shasum=$1", shasum.to_string()).execute(&mut conn).await?;
+ query!("DELETE FROM ships WHERE shasum=$1", shasum.to_string())
+ .execute(&mut conn)
+ .await?;
Ok("OK")
}
-pub async fn get(Path(shasum): Path<Sha256>, state: Extension<Arc<State>>) -> JsonResult<Json<DbShip>> {
+pub async fn get(
+ Path(shasum): Path<Sha256>,
+ state: Extension<Arc<State>>,
+) -> JsonResult<Json<DbShip>> {
let mut conn = state.conn.acquire().await?;
- let db_ship = match query_as!(DbShip, "SELECT * FROM ships WHERE shasum=$1", shasum.to_string()).fetch_one(&mut conn).await {
+ let db_ship = match query_as!(
+ DbShip,
+ "SELECT * FROM ships WHERE shasum=$1",
+ shasum.to_string()
+ )
+ .fetch_one(&mut conn)
+ .await
+ {
Ok(d) => d,
- Err(e) => {
- match e {
- SqlxError::RowNotFound => {
- return Err(ServiceError::NotFound)
- },
- _ => {
- return Err(e.into());
- }
+ Err(e) => match e {
+ SqlxError::RowNotFound => return Err(ServiceError::NotFound),
+ _ => {
+ return Err(e.into());
}
},
};
diff --git a/src/main.rs b/src/main.rs
index 590d714..4a02f95 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -2,14 +2,14 @@ use axum::{
error_handling::HandleErrorLayer,
http::StatusCode,
response::IntoResponse,
- routing::{get, post, delete},
- Json, Router, Extension
+ routing::{delete, get, post},
+ Extension, Json, Router,
};
use errors::ServiceError;
use serde::{Deserialize, Serialize};
-use sqlx::{Connection, query, PgConnection, PgPool, postgres::PgPoolOptions};
-use std::{net::SocketAddr, time::Duration, str::FromStr, sync::Arc};
+use sqlx::{postgres::PgPoolOptions, query, Connection, PgConnection, PgPool};
+use std::{net::SocketAddr, str::FromStr, sync::Arc, time::Duration};
use tower::{BoxError, ServiceBuilder};
use tower_http::trace::TraceLayer;
@@ -28,33 +28,34 @@ pub struct State {
async fn main() {
kankyo::init().unwrap();
color_eyre::install().unwrap();
- tracing_subscriber::registry()
+ tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
- std::env::var("RUST_LOG")
- .unwrap_or_else(|_| "homeworld=info,tower_http=debug".into()),
+ std::env::var("RUST_LOG").unwrap_or_else(|_| "homeworld=info,tower_http=debug".into()),
))
.with(tracing_subscriber::fmt::layer())
.init();
let mut conn = PgPoolOptions::new()
.max_connections(5)
- .connect(&std::env::var("DATABASE_URL").unwrap_or("postgres://postgres@localhost/homeworld".to_string())).await.unwrap();
-
- sqlx::migrate!("./migrations")
- .run(&conn)
- .await.unwrap();
+ .connect(
+ &std::env::var("DATABASE_URL")
+ .unwrap_or("postgres://postgres@localhost/homeworld".to_string()),
+ )
+ .await
+ .unwrap();
- let shared_state = Arc::new(State {
- conn
- });
+ sqlx::migrate!("./migrations").run(&conn).await.unwrap();
+
+ let shared_state = Arc::new(State { conn });
let app = Router::new()
.route("/health", get(health_check))
.route("/ships/list", get(handlers::ships::list))
- .route("/ships/new", post(handlers::ships::new))
+ .route("/ships/new", post(handlers::ships::new))
.route("/ships/delete/:shasum", delete(handlers::ships::delete))
.route("/ships/get/:shasum", get(handlers::ships::get))
- .layer( ServiceBuilder::new()
+ .layer(
+ ServiceBuilder::new()
.layer(HandleErrorLayer::new(|error: BoxError| async move {
if error.is::<tower::timeout::error::Elapsed>() {
Ok(StatusCode::REQUEST_TIMEOUT)
@@ -83,4 +84,3 @@ async fn main() {
async fn health_check() -> &'static str {
"OK"
}
-