summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 31a10ccbb891c94bf3143589c2d94f33edd798ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use axum::{
    Router,
    extract::State,
    http::{Response, StatusCode},
    response::Json,
    routing::{get, post},
};
use chrono::{DateTime, Utc};
use dotenvy::dotenv;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Value, from_value, json};
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::env;
use uuid::Uuid;

const DATABASE_URL_FALLBACK: &str = "postgres://health:health@127.0.0.1:5432/health";

#[derive(sqlx::Type, Serialize, Deserialize)]
#[sqlx(type_name = "metric_type")]
pub enum MetricType {
    BodyWeight,
    Hip,
    Waist,
}

#[derive(sqlx::Type, Serialize, Deserialize)]
#[sqlx(type_name = "unit")]
pub enum Unit {
    Kilogram,
    Centimeter,
}

#[derive(Serialize, Deserialize)]
pub struct Row {
    id: Uuid,
    measured_at: DateTime<Utc>,
    metric_type: MetricType,
    value: f64,
    unit: Unit,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt::init();
    dotenv().ok();
    let database_url =
        env::var("DATABASE_URL").unwrap_or_else(|_| DATABASE_URL_FALLBACK.to_owned());
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect(&database_url)
        .await?;
    let app = Router::new()
        .route("/", get(index))
        .route("/all", get(all))
        .route("/add", post(add))
        .with_state(pool);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    tracing::info!("listening at 0.0.0.0:3000");
    axum::serve(listener, app).await?;
    Ok(())
}

async fn index() -> &'static str {
    "Hello World!"
}

async fn all(State(pool): State<PgPool>) -> Json<Value> {
    let rows = sqlx::query_as!(Row, "SELECT * FROM measurement")
        .fetch_all(&pool)
        .await
        .unwrap_or_else(|_| Vec::new());
    Json(json!(rows))
}

async fn add(State(pool): State<PgPool>, Json(row): Json<Value>) -> StatusCode {
    if let Ok(insert_row) = from_value::<Row>(row) {
        match sqlx::query!("INSERT INTO measurement (id, measured_at, metric_type, value, unit) VALUES ($1, $2, $3, $4, $5)", insert_row.id, insert_row.measured_at, insert_row.metric_type, insert_row.value, insert_row.unit).execute(&pool).await {
            Ok(_) => {return StatusCode::CREATED;},
            Err(sqlx::Error::Database(e)) if e.is_unique_violation() => StatusCode::CONFLICT,
            Err(_) => StatusCode::INTERNAL_SERVER_ERROR 
        }
    } else {
        return StatusCode::UNPROCESSABLE_ENTITY;
    }
}