73 lines
1.7 KiB
Rust
73 lines
1.7 KiB
Rust
use anyhow::Error as AnyError;
|
|
use axum::http::{header, StatusCode, Uri};
|
|
use axum::response::{IntoResponse, Response};
|
|
use axum::{routing::get, Router};
|
|
use sea_orm::{DatabaseConnection, DbErr};
|
|
use thiserror::Error;
|
|
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(())
|
|
}
|
|
|
|
#[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 };
|
|
|
|
let cors = CorsLayer::new()
|
|
.allow_methods(Any)
|
|
.allow_origin(Any)
|
|
.allow_headers([header::CONTENT_TYPE]);
|
|
|
|
Ok(Router::new()
|
|
.route("/", get(|| async { "Hello, world!" }))
|
|
.merge(api::get_routes())
|
|
.fallback(fallback)
|
|
.with_state(state)
|
|
.layer(cors))
|
|
}
|
|
|
|
async fn fallback(uri: Uri) -> (StatusCode, String) {
|
|
(StatusCode::NOT_FOUND, format!("No route for {uri}"))
|
|
}
|
|
|
|
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())
|
|
}
|
|
}
|