use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;
use navree_kernel::{
AppContext, BoxError, BoxFuture, Injectable, KernelError, ModuleBuilder, ModuleId, Resolver,
};
use crate::{AppError, AppRouter, ErrorMapper, RouteDef};
pub trait Controller: Send + Sync + 'static {
fn prefix(&self) -> &'static str;
fn version(&self) -> Option<&'static str> {
None
}
fn routes(self: Arc<Self>) -> Vec<RouteDef>;
}
pub(crate) struct ControllerRoutes {
pub(crate) type_name: &'static str,
pub(crate) prefix: &'static str,
pub(crate) version: Option<&'static str>,
pub(crate) routes: Vec<RouteDef>,
}
type ResolveRoutes = Arc<
dyn Fn(Resolver) -> BoxFuture<'static, Result<ControllerRoutes, KernelError>> + Send + Sync,
>;
#[derive(Clone)]
pub(crate) struct ControllerRegistration {
pub(crate) module: ModuleId,
pub(crate) resolve: ResolveRoutes,
}
impl ControllerRegistration {
fn of<C: Controller + Injectable>(module: ModuleId) -> Self {
Self {
module,
resolve: Arc::new(|r: Resolver| {
Box::pin(async move {
let controller = r.get::<C>().await?;
Ok(ControllerRoutes {
type_name: std::any::type_name::<C>(),
prefix: controller.prefix(),
version: controller.version(),
routes: controller.routes(),
})
})
}),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum LayerSlot {
Edge,
Session,
AuthContext,
Uow,
Context,
}
pub type ApplyLayer =
Arc<dyn Fn(&AppContext, AppRouter) -> Result<AppRouter, BoxError> + Send + Sync>;
#[derive(Clone)]
pub struct GlobalLayer {
pub slot: LayerSlot,
pub name: &'static str,
pub apply: ApplyLayer,
}
impl GlobalLayer {
pub fn new<F>(slot: LayerSlot, name: &'static str, apply: F) -> Self
where
F: Fn(&AppContext, AppRouter) -> Result<AppRouter, BoxError> + Send + Sync + 'static,
{
Self {
slot,
name,
apply: Arc::new(apply),
}
}
}
impl fmt::Debug for GlobalLayer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GlobalLayer")
.field("slot", &self.slot)
.field("name", &self.name)
.finish_non_exhaustive()
}
}
pub trait ModuleBuilderHttpExt {
fn controller<C: Controller + Injectable>(&mut self) -> &mut Self;
fn http_layer(&mut self, layer: GlobalLayer) -> &mut Self;
fn map_error<E: StdError + 'static>(&mut self, f: fn(&E) -> Option<AppError>) -> &mut Self;
fn error_pages(&mut self, pages: impl crate::ErrorPages) -> &mut Self;
}
impl ModuleBuilderHttpExt for ModuleBuilder {
fn controller<C: Controller + Injectable>(&mut self) -> &mut Self {
let registration = ControllerRegistration::of::<C>(self.module_id());
self.provider::<C>().contribute(registration)
}
fn http_layer(&mut self, layer: GlobalLayer) -> &mut Self {
self.contribute(layer)
}
fn map_error<E: StdError + 'static>(&mut self, f: fn(&E) -> Option<AppError>) -> &mut Self {
self.contribute(ErrorMapper::new(f))
}
fn error_pages(&mut self, pages: impl crate::ErrorPages) -> &mut Self {
self.contribute(crate::ErrorPagesHandle::new(pages))
}
}