Skip to main content

graphile_worker_lifecycle_hooks/
registry.rs

1use std::future::Future;
2
3use futures::future::BoxFuture;
4
5use crate::event::Event;
6use crate::plugin::Plugin;
7use crate::TypeErasedHooks;
8
9#[derive(Default)]
10pub struct HookRegistry {
11    pub(crate) inner: TypeErasedHooks,
12}
13
14impl HookRegistry {
15    pub fn new() -> Self {
16        Self::default()
17    }
18
19    pub fn on<E, F, Fut>(&mut self, _event: E, handler: F) -> &mut Self
20    where
21        E: Event,
22        F: Fn(E::Context) -> Fut + Send + Sync + Clone + 'static,
23        Fut: Future<Output = E::Output> + Send + 'static,
24    {
25        let boxed: Box<dyn Fn(E::Context) -> BoxFuture<'static, E::Output> + Send + Sync> =
26            Box::new(move |ctx| {
27                let fut = handler(ctx);
28                Box::pin(fut)
29            });
30        E::register_boxed(&mut self.inner, boxed);
31        self
32    }
33
34    pub fn with_plugin<P: Plugin>(mut self, plugin: P) -> Self {
35        plugin.register(&mut self);
36        self
37    }
38}