renox_core/module.rs
1use crate::db::Migration;
2use crate::{Registry, Routes};
3
4/// A self-contained piece of an application: its routes and migrations, and
5/// later its jobs, policies and views.
6///
7/// ```
8/// # use renox::prelude::*;
9/// # async fn index() -> &'static str { "" }
10/// # async fn show() -> &'static str { "" }
11/// pub struct Products;
12///
13/// impl Module for Products {
14/// fn name(&self) -> &'static str { "products" }
15///
16/// fn routes(&self) -> Routes {
17/// Routes::new()
18/// .get("/products", index).name("products.index")
19/// .get("/products/{id}", show).name("products.show")
20/// }
21/// }
22/// ```
23pub trait Module: Send + Sync + 'static {
24 /// The module's name, shown by `route:list`.
25 fn name(&self) -> &'static str;
26
27 /// The module's routes; none by default.
28 fn routes(&self) -> Routes {
29 Routes::new()
30 }
31
32 /// Migrations this module owns, e.g. `renox::migrations!("src/app/products/migrations")`.
33 fn migrations(&self) -> &'static [Migration] {
34 &[]
35 }
36
37 /// Registers the module's jobs, event listeners and scheduled tasks.
38 ///
39 /// ```
40 /// # use renox::prelude::*;
41 /// # use serde::{Deserialize, Serialize};
42 /// # #[derive(Serialize, Deserialize)] struct SendReceipt { order_id: i64 }
43 /// # impl Job for SendReceipt { const NAME: &'static str = "send-receipt"; async fn handle(self, _: JobContext) -> Result { Ok(()) } }
44 /// # #[derive(Clone)] struct OrderPlaced { order_id: i64 }
45 /// # impl Event for OrderPlaced {}
46 /// # async fn close_day(_: AppState) -> Result { Ok(()) }
47 /// # struct Orders;
48 /// # impl Module for Orders {
49 /// # fn name(&self) -> &'static str { "orders" }
50 /// fn register(&self, app: &mut Registry) {
51 /// app.job::<SendReceipt>()
52 /// .listen(|e: OrderPlaced, state| async move {
53 /// state.dispatch(SendReceipt { order_id: e.order_id }).await?;
54 /// Ok(())
55 /// });
56 /// app.schedule().daily_at("02:00", "close-day", close_day);
57 /// }
58 /// # }
59 /// ```
60 fn register(&self, _app: &mut Registry) {}
61}