lyrs/src/router.rs

90 lines
2.2 KiB
Rust
Raw Normal View History

2024-05-20 11:35:39 -05:00
use crate::partials::page;
use crate::{
file_watcher::FileWatcher,
prelude::*,
service::{auth, static_files},
state::State as AppState,
};
2024-05-15 16:48:23 -05:00
use axum::{
2024-05-17 12:00:37 -05:00
http::StatusCode,
2024-05-15 16:48:23 -05:00
response::{Html, IntoResponse},
2024-05-20 11:35:39 -05:00
routing::get,
Router,
2024-05-15 16:48:23 -05:00
};
2024-05-20 11:35:39 -05:00
use maud::html;
2024-05-15 16:48:23 -05:00
use thiserror::Error;
2024-05-17 12:00:37 -05:00
use tower_http::trace::TraceLayer;
use tower_livereload::LiveReloadLayer;
2024-05-15 16:48:23 -05:00
#[derive(Error, Debug)]
pub enum NewRouterError {
#[error("watcher error: {0}")]
Watcher(#[from] notify::Error),
}
#[derive(Error, Debug)]
2024-05-20 11:35:39 -05:00
pub enum ReqError {
#[error("argon2 error: {0}")]
Argon2(#[from] argon2::password_hash::Error),
}
2024-05-15 16:48:23 -05:00
impl IntoResponse for ReqError {
fn into_response(self) -> axum::http::Response<axum::body::Body> {
error!("webserver error: {:?}", self);
(
StatusCode::INTERNAL_SERVER_ERROR,
// TODO: don't expose raw errors over the internet?
format!("internal server error: {}", self),
)
.into_response()
}
}
pub type ReqResult<T> = Result<T, ReqError>;
pub async fn router(
2024-05-17 12:00:37 -05:00
state: AppState,
2024-05-15 16:48:23 -05:00
with_watchers: bool,
) -> Result<(Router, Vec<Option<FileWatcher>>), NewRouterError> {
2024-05-14 15:33:49 -05:00
let live_reload_layer: Option<LiveReloadLayer> = if with_watchers {
Some(LiveReloadLayer::new())
} else {
None
};
2024-05-14 14:30:03 -05:00
2024-05-14 15:33:49 -05:00
let orl = || {
if let Some(lr) = &live_reload_layer {
Some(lr.reloader())
} else {
None
}
};
let (static_file_service, static_file_watcher) = static_files::router(orl())?;
2024-05-20 11:35:39 -05:00
let auth_service = auth::router().unwrap();
2024-05-14 15:33:49 -05:00
let mut result = Router::new()
2024-05-14 14:30:03 -05:00
.route("/", get(index))
2024-05-14 16:56:22 -05:00
.route("/about", get(about))
2024-05-20 11:35:39 -05:00
.nest_service("/auth", auth_service)
2024-05-14 14:30:03 -05:00
.nest_service("/static", static_file_service)
2024-05-17 12:00:37 -05:00
.layer(TraceLayer::new_for_http())
2024-05-14 15:33:49 -05:00
.with_state(state.clone());
if let Some(lr) = live_reload_layer {
result = result.clone().layer(lr);
}
2024-05-17 12:00:37 -05:00
let watchers = vec![static_file_watcher];
2024-05-14 15:33:49 -05:00
Ok((result, watchers))
2024-05-14 14:30:03 -05:00
}
2024-05-17 12:00:37 -05:00
async fn index() -> ReqResult<Html<String>> {
page("index", html! { "Index" })
}
async fn about() -> ReqResult<Html<String>> {
page("index", html! { "About" })
}