Skip to main content

json_gettext/common/rocket_feature/reloadable/
json_get_text_fairing.rs

1use rocket::{
2    Build, Rocket,
3    data::Data,
4    fairing::{Fairing, Info, Kind},
5    request::Request,
6};
7
8use super::JSONGetTextManager;
9
10const FAIRING_NAME: &str = "JSONGetText (Debug)";
11
12/// The fairing of `JSONGetTextManager`.
13#[allow(clippy::type_complexity)]
14pub struct JSONGetTextFairing {
15    pub(crate) custom_callback:
16        Box<dyn Fn() -> (crate::Key, Vec<(crate::Key, &'static str)>) + Send + Sync + 'static>,
17}
18
19#[rocket::async_trait]
20impl Fairing for JSONGetTextFairing {
21    #[inline]
22    fn info(&self) -> Info {
23        Info {
24            name: FAIRING_NAME, kind: Kind::Ignite | Kind::Request
25        }
26    }
27
28    #[inline]
29    async fn on_ignite(&self, rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>> {
30        let (default_key, source) = (self.custom_callback)();
31
32        let state = JSONGetTextManager::from_files(default_key, source).unwrap();
33
34        Ok(rocket.manage(state))
35    }
36
37    #[inline]
38    async fn on_request(&self, req: &mut Request<'_>, _data: &mut Data<'_>) {
39        let ctx = req
40            .rocket()
41            .state::<JSONGetTextManager>()
42            .expect("JSONGetTextManager registered in on_attach");
43
44        ctx.reload_if_needed().unwrap();
45    }
46}