Files
Krys4lide/crates/backend/src/lib.rs

73 lines
1.7 KiB
Rust
Raw Normal View History

2024-09-23 18:55:31 +02:00
use anyhow::Error as AnyError;
2024-09-24 17:54:02 +02:00
use axum::http::{header, StatusCode, Uri};
2024-09-23 18:55:31 +02:00
use axum::response::{IntoResponse, Response};
2024-09-23 18:02:07 +02:00
use axum::{routing::get, Router};
use sea_orm::{DatabaseConnection, DbErr};
use thiserror::Error;
2024-09-24 17:54:02 +02:00
use tower_http::cors::{Any, CorsLayer};
use ::utils::config::{load_config, ConfigError};
mod api;
mod db;
#[derive(Error, Debug)]
pub enum InitError {
#[error(transparent)]
ConfigError(#[from] ConfigError),
}
pub fn init() -> Result<(), InitError> {
load_config(None)?;
Ok(())
}
2024-09-23 18:02:07 +02:00
#[derive(Clone)]
pub struct AppState {
db_connection: DatabaseConnection,
}
pub async fn get_router() -> Result<Router, DbErr> {
let db_connection = db::get_connection().await?;
let state: AppState = AppState { db_connection };
2024-09-24 17:54:02 +02:00
let cors = CorsLayer::new()
.allow_methods(Any)
.allow_origin(Any)
.allow_headers([header::CONTENT_TYPE]);
Ok(Router::new()
2024-09-23 18:02:07 +02:00
.route("/", get(|| async { "Hello, world!" }))
.merge(api::get_routes())
.fallback(fallback)
2024-09-24 17:54:02 +02:00
.with_state(state)
.layer(cors))
2024-09-23 18:02:07 +02:00
}
async fn fallback(uri: Uri) -> (StatusCode, String) {
(StatusCode::NOT_FOUND, format!("No route for {uri}"))
}
2024-09-23 18:55:31 +02:00
struct AppError(AnyError);
// To automatically convert `AppError` into a response
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Internal Server Error: {}", self.0),
)
.into_response()
}
}
// To automatically convert `AnyError` into `AppError`
impl<E> From<E> for AppError
where
E: Into<AnyError>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}