modulink_rs/middleware/
mod.rs

1//! Middleware trait for modulink-rust
2//! Trait with async before/after hooks.
3
4use crate::context::Context;
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::Arc;
8
9pub trait Middleware<T>: Send + Sync {
10    fn before<'a>(&'a self, ctx: &'a T) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
11        Box::pin(async move { let _ = ctx; })
12    }
13    fn after<'a>(&'a self, ctx: &'a T) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
14        Box::pin(async move { let _ = ctx; })
15    }
16}
17
18pub type MiddlewareObj = Arc<dyn Middleware<Context>>;
19
20// Built-in Logging middleware
21pub struct LoggingMiddleware;
22
23impl Middleware<Context> for LoggingMiddleware {
24    fn before<'a>(&'a self, ctx: &'a Context) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
25        let ctx = ctx.clone();
26        Box::pin(async move {
27            println!("[Logging] Before: {:?}", ctx);
28        })
29    }
30    fn after<'a>(&'a self, ctx: &'a Context) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
31        let ctx = ctx.clone();
32        Box::pin(async move {
33            println!("[Logging] After: {:?}", ctx);
34        })
35    }
36}
37
38pub fn logging_middleware() -> MiddlewareObj {
39    Arc::new(LoggingMiddleware)
40}