1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
use crate::{ context::{Context, DefaultContext}, error::Error, }; use std::{fmt::Debug, future::Future, pin::Pin}; pub type NextHandler<TContext> = Box< dyn Fn(TContext) -> Pin<Box<dyn Future<Output = Result<TContext, Error<TContext>>> + Send>> + Send + Sync, >; #[async_trait::async_trait] pub trait Middleware<TContext: Context + Debug + Send + Sync> { async fn run_middleware( &self, context: TContext, next: NextHandler<TContext>, ) -> Result<TContext, Error<TContext>>; } type DefaultMiddlewareHandler = fn( DefaultContext, NextHandler<DefaultContext>, ) -> Pin<Box<dyn Future<Output = Result<DefaultContext, Error<DefaultContext>>> + Send>>; #[derive(Clone)] pub struct DefaultMiddleware<TData> where TData: Default + Clone + Send + Sync, { handler: DefaultMiddlewareHandler, data: TData, } impl<TData> DefaultMiddleware<TData> where TData: Default + Clone + Send + Sync, { pub fn new(handler: DefaultMiddlewareHandler) -> Self { DefaultMiddleware { handler, data: Default::default(), } } pub fn new_with_data(handler: DefaultMiddlewareHandler, data: TData) -> Self { DefaultMiddleware { handler, data } } } #[async_trait::async_trait] impl<TData> Middleware<DefaultContext> for DefaultMiddleware<TData> where TData: Default + Clone + Send + Sync, { async fn run_middleware( &self, context: DefaultContext, next: NextHandler<DefaultContext>, ) -> Result<DefaultContext, Error<DefaultContext>> { (self.handler)(context, next).await } }