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
use std::sync::{Mutex, MutexGuard, PoisonError};

use super::{FileResources, StaticContextManager, StaticResponse};
use crate::rocket::{
    fairing::{Fairing, Info, Kind},
    Build, Rocket,
};

const FAIRING_NAME: &str = "Static Resources (Debug)";

/// The fairing of `StaticResponse`.
pub struct StaticResponseFairing {
    #[allow(clippy::type_complexity)]
    pub(crate) custom_callback: Box<dyn Fn(&mut MutexGuard<FileResources>) + Send + Sync + 'static>,
}

#[rocket::async_trait]
impl Fairing for StaticResponseFairing {
    #[inline]
    fn info(&self) -> Info {
        Info {
            name: FAIRING_NAME, kind: Kind::Ignite
        }
    }

    #[inline]
    async fn on_ignite(&self, rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>> {
        let resources = Mutex::new(FileResources::new());

        (self.custom_callback)(&mut resources.lock().unwrap_or_else(PoisonError::into_inner));

        let state = StaticContextManager::new(resources);

        Ok(rocket.manage(state))
    }
}

impl StaticResponse {
    #[inline]
    /// Create the fairing of `HandlebarsResponse`.
    pub fn fairing<F>(f: F) -> impl Fairing
    where
        F: Fn(&mut MutexGuard<FileResources>) + Send + Sync + 'static, {
        StaticResponseFairing {
            custom_callback: Box::new(f)
        }
    }
}