yooso_api/
lib.rs

1//! TODO: document
2
3mod components;
4mod entities;
5mod logs;
6
7use rocket::{Build, Ignite, Rocket};
8use rocket_cors::{Cors, CorsOptions};
9use yooso_storage::{ComponentFieldTable, ComponentTable, EntityTable, GeneralDBState, LogDBState, LogRecordTable, MetaDBState};
10
11/// TODO: document
12pub struct Yooso {
13    /// Inner [Rocket] instance. [Rocket] is the underlying web framework used
14    /// by [Yooso] to provide an HTTP layer.
15    pub(crate) rocket: Rocket<Build>,
16}
17
18impl Yooso {
19    /// Creates a [Yooso] instance with the default config provider for [Rocket].
20    pub async fn build() -> Self {
21        let general_db_state = GeneralDBState::default();
22        let meta_db_state = MetaDBState::default();
23        let log_db_state = LogDBState::default();
24
25        EntityTable::create_table(&meta_db_state).await
26            .expect("failed to create table: `entities`");
27        ComponentTable::create_table(&meta_db_state).await
28            .expect("failed to create table: `components`");
29        ComponentFieldTable::create_table(&meta_db_state).await
30            .expect("failed to create table: `component_fields`");
31        LogRecordTable::create_table(&log_db_state).await
32            .expect("failed to create table: `logs`");
33
34        Self {
35            rocket: rocket::build()
36                .manage(general_db_state)
37                .manage(meta_db_state)
38                .manage(log_db_state)
39                .mount("/api/components", crate::components::routes())
40                .mount("/api/entities", crate::entities::routes())
41                .mount("/api/logs", crate::logs::routes())
42                .attach(Self::cors_config())
43                .attach(logs::LogFairing)
44        }
45    }
46
47    /// Private constructor for CORS configuration. This is used internally by the
48    /// CORS fairing.
49    pub(self) fn cors_config() -> Cors {
50        let options = CorsOptions::default();
51        Cors::from_options(&options).unwrap()
52    }
53
54    /// Launches the [Yooso] application, consuming the instance in the process.
55    pub async fn launch(self) -> Rocket<Ignite> {
56        self.rocket.launch().await.unwrap()
57    }
58}