dermy-api/src/lib.rs

78 lines
2.2 KiB
Rust
Raw Normal View History

2024-06-06 18:21:12 +00:00
mod account;
mod model;
2024-06-07 14:30:16 +00:00
use account::db::{User, get_db_client};
2024-06-07 01:24:42 +00:00
use anyhow::Result;
2024-06-07 14:30:16 +00:00
use axum::response::{IntoResponse, Response};
2024-06-07 01:24:42 +00:00
use axum_session::{SessionConfig, SessionLayer, SessionStore};
use axum_session_auth::{AuthConfig, AuthSessionLayer};
use axum_session_mongo::SessionMongoPool;
2024-06-07 14:30:16 +00:00
use http::StatusCode;
2024-06-07 01:24:42 +00:00
use mongodb::{bson::oid::ObjectId, Client};
2024-06-07 17:59:35 +00:00
use rlg::{config::Config, macro_info_log};
2024-06-07 01:24:42 +00:00
pub async fn run() -> Result<()> {
2024-06-07 17:59:35 +00:00
init_logging();
macro_info_log!(&chrono::Utc::now().to_string(), "server", "Server Initializing...");
2024-06-07 14:30:16 +00:00
let db = get_db_client().await?;
2024-06-07 01:24:42 +00:00
let session_store = session(db.clone()).await?;
let auth_config = AuthConfig::<ObjectId>::default();
2024-06-07 17:59:35 +00:00
macro_info_log!(&chrono::Utc::now().to_string(), "server", "Routes Initializing...");
2024-06-07 01:24:42 +00:00
let app = router()
.layer(SessionLayer::new(session_store))
.layer(AuthSessionLayer::<User, ObjectId, SessionMongoPool, Client>
::new(Some(db)).with_config(auth_config)
);
2024-06-07 17:59:35 +00:00
macro_info_log!(&chrono::Utc::now().to_string(), "server", "Routes Initialized");
2024-06-06 18:25:03 +00:00
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
2024-06-07 01:24:42 +00:00
axum::serve(listener, app).await?;
2024-06-07 17:59:35 +00:00
macro_info_log!(&chrono::Utc::now().to_string(), "server", "Server Initialized");
2024-06-07 01:24:42 +00:00
Ok(())
2024-06-06 18:25:03 +00:00
}
fn router() -> axum::Router {
2024-06-06 18:21:12 +00:00
axum::Router::new()
.nest("/account", account::router())
2024-06-07 17:59:35 +00:00
//.nest("/predict", model::router())
2024-06-06 18:21:12 +00:00
}
2024-06-07 01:24:42 +00:00
async fn session(db: Client) -> Result<SessionStore<SessionMongoPool>> {
let session_config = SessionConfig::default()
.with_table_name("sessions");
Ok(SessionStore::<SessionMongoPool>
::new(Some(db.clone().into()), session_config).await?)
}
2024-06-07 14:30:16 +00:00
struct AppError(anyhow::Error);
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}
2024-06-07 17:59:35 +00:00
fn init_logging() {
std::env::set_var("LOG_FILE_PATH", "$HOME/.dermy/server.log");
let config = Config::load();
}