use std::collections::HashSet;
use std::sync::Arc;
use axum::routing::{get, post};
use axum::Router;
use crate::sql::sqlx::PgPool;
use super::views;
pub fn router(pool: PgPool) -> Router {
Builder::new(pool).build()
}
#[must_use]
pub struct Builder {
pool: PgPool,
config: Config,
}
#[derive(Clone, Default)]
pub(crate) struct Config {
pub(crate) allowed_tables: Option<HashSet<String>>,
pub(crate) read_only_tables: HashSet<String>,
pub(crate) read_only_all: bool,
}
impl Builder {
pub fn new(pool: PgPool) -> Self {
Self {
pool,
config: Config::default(),
}
}
pub fn show_only<I, S>(mut self, tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.config.allowed_tables = Some(tables.into_iter().map(Into::into).collect());
self
}
pub fn read_only<I, S>(mut self, tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.config
.read_only_tables
.extend(tables.into_iter().map(Into::into));
self
}
pub fn read_only_all(mut self) -> Self {
self.config.read_only_all = true;
self
}
pub fn build(self) -> Router {
Router::new()
.route("/", get(views::index))
.route("/{table}", get(views::table_view).post(views::create_submit))
.route("/{table}/new", get(views::create_form))
.route(
"/{table}/{pk}",
get(views::detail_view).post(views::update_submit),
)
.route("/{table}/{pk}/edit", get(views::edit_form))
.route("/{table}/{pk}/delete", post(views::delete_submit))
.with_state(AppState {
pool: self.pool,
config: Arc::new(self.config),
})
}
}
#[derive(Clone)]
pub(crate) struct AppState {
pub(crate) pool: PgPool,
pub(crate) config: Arc<Config>,
}
impl AppState {
pub(crate) fn is_visible(&self, table: &str) -> bool {
self.config
.allowed_tables
.as_ref()
.is_none_or(|allowed| allowed.contains(table))
}
pub(crate) fn is_read_only(&self, table: &str) -> bool {
self.config.read_only_all || self.config.read_only_tables.contains(table)
}
}