From 3e6a72428824c5a50a873a4284b86d0a9e47a778 Mon Sep 17 00:00:00 2001 From: fx Date: Mon, 9 Oct 2023 17:26:59 +0200 Subject: db int for api --- src/main.rs | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index 761e925..bb37dc2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,13 @@ +use std::env; use std::sync::Arc; use axum::{Router, routing::post}; -use sqlx::SqlitePool; +use axum::routing::{get, put}; +use sqlx::PgPool; +use sqlx::postgres::PgPoolOptions; use time::util::local_offset; use tracing::{debug, info, level_filters::LevelFilter}; use tracing_subscriber::{EnvFilter, fmt::{self, time::LocalTime}, prelude::*}; +use crate::routes::device::{get_device, post_device, put_device}; use crate::routes::start::start; mod auth; @@ -11,6 +15,7 @@ mod config; mod routes; mod wol; mod db; +mod error; #[tokio::main] async fn main() { @@ -30,20 +35,20 @@ async fn main() { ) .init(); - debug!("connecting to db"); - let db = SqlitePool::connect("sqlite:devices.sqlite").await.unwrap(); - sqlx::migrate!().run(&db).await.unwrap(); - info!("connected to db"); - let version = env!("CARGO_PKG_VERSION"); info!("starting webol v{}", version); + let db = init_db_pool().await; + let shared_state = Arc::new(AppState { db }); // build our application with a single route let app = Router::new() .route("/start", post(start)) + .route("/device", get(get_device)) + .route("/device", put(put_device)) + .route("/device", post(post_device)) .with_state(shared_state); // run it with hyper on localhost:3000 @@ -54,5 +59,21 @@ async fn main() { } pub struct AppState { - db: SqlitePool + db: PgPool +} + +async fn init_db_pool() -> PgPool { + let db_url = env::var("DATABASE_URL").unwrap(); + + debug!("attempting to connect dbPool to '{}'", db_url); + + let pool = PgPoolOptions::new() + .max_connections(5) + .connect(&db_url) + .await + .unwrap(); + + info!("dbPool successfully connected to '{}'", db_url); + + pool } \ No newline at end of file -- cgit v1.2.3