use std::sync::Arc;
use actix_web::web::Data;
use secrecy::ExposeSecret;
use crate::config::app::Config;
use crate::db::connection;
use crate::keycloak_api;
use crate::sse::broadcaster::Broadcaster;
pub type SharedPool = Data<connection::Pool>;
pub type SharedBroadcaster = Data<Broadcaster>;
pub type SharedKeycloakApi = Data<dyn keycloak_api::traits::KeycloakApi + Send + Sync + 'static>;
pub type SharedHttpClient = Data<reqwest::Client>;
pub struct SharedInit {
pub pool: SharedPool,
pub broadcaster: SharedBroadcaster,
pub keycloak_api: SharedKeycloakApi,
pub http_client: SharedHttpClient,
}
#[must_use]
pub fn init(config: &Config) -> SharedInit {
let api = Data::from(create_api(config));
SharedInit {
keycloak_api: api,
pool: Data::new(connection::init_pool(config.database_url.expose_secret())),
broadcaster: Data::new(Broadcaster::new()),
http_client: Data::new(reqwest::Client::new()),
}
}
#[must_use]
pub fn create_api(
config: &Config,
) -> Arc<dyn keycloak_api::traits::KeycloakApi + Send + Sync + 'static> {
if let (Some(client_id), Some(client_secret)) = (
config.auth_admin_client_id.clone(),
config.auth_admin_client_secret.clone(),
) {
Arc::new(keycloak_api::api::Api::new(keycloak_api::api::Config {
token_url: config.auth_token_uri.clone(),
client_id,
client_secret,
}))
} else {
log::info!("Using mock Keycloak API");
Arc::new(keycloak_api::mock_api::MockApi)
}
}