moduforge_core/
middleware.rs1use std::sync::Arc;
2
3use crate::error::EditorResult;
4use moduforge_state::{transaction::Transaction, state::State};
5
6pub struct MiddlewareResult {
8 pub result: EditorResult<()>,
10 pub additional_transaction: Option<Transaction>,
12}
13
14impl MiddlewareResult {
15 pub fn new(result: EditorResult<()>) -> Self {
17 Self { result, additional_transaction: None }
18 }
19
20 pub fn with_transactions(
22 result: EditorResult<()>,
23 transaction: Option<Transaction>,
24 ) -> Self {
25 Self { result, additional_transaction: transaction }
26 }
27}
28
29#[async_trait::async_trait]
31pub trait Middleware: Send + Sync {
32 async fn before_dispatch(
34 &self,
35 transaction: &mut Transaction,
36 ) -> EditorResult<()>;
37
38 async fn after_dispatch(
41 &self,
42 state: Option<Arc<State>>,
43 ) -> EditorResult<MiddlewareResult>;
44}
45
46pub type BoxedMiddleware = Box<dyn Middleware>;
48
49pub struct MiddlewareStack {
51 pub middlewares: Vec<BoxedMiddleware>,
52}
53
54impl MiddlewareStack {
55 pub fn new() -> Self {
56 Self { middlewares: Vec::new() }
57 }
58
59 pub fn add<M>(
60 &mut self,
61 middleware: M,
62 ) where
63 M: Middleware + 'static,
64 {
65 self.middlewares.push(Box::new(middleware));
66 }
67
68 pub fn is_empty(&self) -> bool {
69 self.middlewares.is_empty()
70 }
71}
72
73impl Default for MiddlewareStack {
74 fn default() -> Self {
75 Self::new()
76 }
77}