Added config file for db (#9)
Some checks failed
Release Tagging / release (push) Successful in 47s
Rust Build / Check (push) Successful in 53s
Rust Build / Test Suite (push) Failing after 54s
Rust Build / Rustfmt (push) Successful in 28s
Rust Build / Clippy (push) Successful in 50s
Rust Build / build (push) Successful in 1m5s

Reviewed-on: #9
Co-authored-by: KD <kundeng94@gmail.com>
Co-committed-by: KD <kundeng94@gmail.com>
This commit is contained in:
KD
2025-04-03 13:59:54 +00:00
committed by phoenix
parent c9873d95d7
commit 4d3415acf2
11 changed files with 272 additions and 9 deletions

View File

@@ -1,4 +1,30 @@
use axum::{Extension, Json, http::StatusCode};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
pub struct TestResult {
message: String,
}
// basic handler that responds with a static string
pub async fn root() -> &'static str {
"Hello, World!"
}
pub async fn db_ping(Extension(pool): Extension<sqlx::PgPool>) -> (StatusCode, Json<TestResult>) {
match sqlx::query("SELECT 1").execute(&pool).await {
Ok(_) => {
let tr = TestResult {
message: String::from("This works"),
};
(StatusCode::OK, Json(tr))
}
Err(e) => (
StatusCode::BAD_REQUEST,
Json(TestResult {
message: e.to_string(),
}),
),
}
}

View File

@@ -3,5 +3,6 @@ pub mod register;
pub mod endpoints {
pub const ROOT: &str = "/";
pub const REGISTER: &str = "api/v2/register";
pub const REGISTER: &str = "/api/v2/register";
pub const DBTEST: &str = "/api/v2/test/db";
}

View File

@@ -1,3 +1,33 @@
pub mod callers;
pub mod config;
pub mod models;
mod keys {
pub const DBURL: &str = "DATABASE_URL";
pub mod error {
pub const ERROR: &str = "DATABASE_URL must be set in .env";
}
}
mod connection_settings {
pub const MAXCONN: u32 = 5;
}
pub mod db_pool {
use sqlx::postgres::PgPoolOptions;
use std::env;
use crate::{connection_settings, keys};
pub async fn create_pool() -> Result<sqlx::PgPool, sqlx::Error> {
dotenv::dotenv().ok();
let database_url = env::var(keys::DBURL).expect(keys::error::ERROR);
PgPoolOptions::new()
.max_connections(connection_settings::MAXCONN)
.connect(&database_url)
.await
}
}

View File

@@ -2,25 +2,92 @@ use axum::{
Router,
routing::{get, post},
};
// use std::net::SocketAddr;
use icarus_auth::callers;
use icarus_auth::config;
// use sqlx::Postgres;
#[tokio::main]
async fn main() {
// initialize tracing
tracing_subscriber::fmt::init();
// build our application with a route
let app = Router::new()
.route(callers::endpoints::ROOT, get(callers::common::root))
.route(
callers::endpoints::REGISTER,
post(callers::register::register_user),
);
let app = app().await;
// run our app with hyper, listening globally on port 3000
let url = config::get_full();
let listener = tokio::net::TcpListener::bind(url).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn app() -> Router {
let pool = icarus_auth::db_pool::create_pool()
.await
.expect("Failed to create pool");
// build our application with a route
Router::new()
.route(callers::endpoints::DBTEST, get(callers::common::db_ping))
.route(callers::endpoints::ROOT, get(callers::common::root))
.route(
callers::endpoints::REGISTER,
post(callers::register::register_user),
)
.layer(axum::Extension(pool))
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
// extract::connect_info::MockConnectInfo,
http::{Request, StatusCode},
};
use http_body_util::BodyExt;
// use http_body_util::BodyExt; // for `collect`
// use serde_json::{Value, json};
// use tokio::net::TcpListener;
// use tower::{Service, ServiceExt}; // for `call`, `oneshot`, and `ready`
use tower::ServiceExt; // for `call`, `oneshot`, and `ready`
#[tokio::test]
async fn hello_world() {
let app = app().await;
// `Router` implements `tower::Service<Request<Body>>` so we can
// call it like any tower service, no need to run an HTTP server.
let response = app
.oneshot(
Request::builder()
.uri(callers::endpoints::ROOT)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
/*
match response.into_body().collect().await {
Ok(o) => {
let parsed: String = match String::from_utf8(o.to_bytes()) {
Ok(s) => s,
Err(err) => {
String::new()
}
};
}
Err(err) => {
assert!(false,
"Error: {:?}", err.to_string());
}
}
*/
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&body[..], b"Hello, World!");
}
}