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 transactions: &[Transaction],
44 ) -> EditorResult<MiddlewareResult>;
45}
46
47pub type ArcMiddleware = Arc<dyn Middleware>;
49
50#[derive(Clone)]
52pub struct MiddlewareStack {
53 pub middlewares: Vec<ArcMiddleware>,
54}
55
56impl MiddlewareStack {
57 pub fn new() -> Self {
58 Self { middlewares: Vec::new() }
59 }
60
61 pub fn add<M>(
62 &mut self,
63 middleware: M,
64 ) where
65 M: Middleware + 'static,
66 {
67 self.middlewares.push(Arc::new(middleware));
68 }
69
70 pub fn is_empty(&self) -> bool {
71 self.middlewares.is_empty()
72 }
73}
74
75impl Default for MiddlewareStack {
76 fn default() -> Self {
77 Self::new()
78 }
79}