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
use crate::ServiceData;
use async_trait::async_trait;
use std::fmt::{Debug, Formatter};
use std::sync::Arc;

pub enum WrapperResult {
    Continue,
    Return,
}

#[async_trait]
pub trait WrapperFn {
    fn name(&self) -> &str;
    async fn before(&self, data: &mut ServiceData) -> WrapperResult;
    async fn after(&self, data: &mut ServiceData) -> WrapperResult;
}
impl Debug for (dyn WrapperFn + Send + Sync + 'static) {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name())
    }
}

#[derive(Clone, Debug)]
pub struct Wrapper {
    name: String,
    wrapper_functions: Vec<Arc<dyn WrapperFn + Sync + Send>>,
}
#[async_trait]
impl WrapperFn for Wrapper {
    fn name(&self) -> &str {
        &self.name
    }

    async fn before(&self, data: &mut ServiceData) -> WrapperResult {
        for func in self.wrapper_functions.iter() {
            match func.before(data).await {
                WrapperResult::Continue => continue,
                WrapperResult::Return => {
                    return WrapperResult::Return;
                }
            }
        }
        WrapperResult::Continue
    }

    async fn after(&self, data: &mut ServiceData) -> WrapperResult {
        for func in self.wrapper_functions.iter() {
            match func.after(data).await {
                WrapperResult::Continue => continue,
                WrapperResult::Return => {
                    return WrapperResult::Return;
                }
            }
        }
        WrapperResult::Continue
    }
}