yao-dev-common 0.1.10

Common library
Documentation
use apollo_client::conf::requests::CachedFetchRequest;
use apollo_client::conf::ApolloConfClientBuilder;
use dotenv::dotenv;
use ini::Properties;
use std::env;
use std::error::Error;
use url::Url;

/// 项目配置初始化。首先从 .env 中读取。如果没有,从 Apollo 读取配置信息。
///
/// Apollo 的 meta 信息和 namespace 信息从环境变量中读取。
pub async fn apollo_settings() -> Result<Vec<Properties>, Box<dyn Error>> {
    dotenv().ok();
    // url
    // let database_url = env::var("database.url").expect("database.url must be set");
    let mut apollo_meta = env::var("apollo.meta").expect("apollo.meta must be set");
    if apollo_meta.is_empty() {
        apollo_meta = "http://127.0.0.1:8080".to_string();
    }
    let mut app_id = env::var("app.id").expect("app.id must be set");
    if app_id.is_empty() {
        app_id = "default".to_string()
    }
    let mut apollo_namespaces = vec![];
    let apollo_namespaces_str =
        env::var("apollo.namespaces").expect("apollo.namespaces must be set");
    if apollo_namespaces_str.is_empty() {
        apollo_namespaces = vec!["application".to_string()]
    } else {
        apollo_namespaces = apollo_namespaces_str
            .split(',')
            .map(|s| s.to_string())
            .collect();
    }

    let apollo_client =
        ApolloConfClientBuilder::new_via_config_service(Url::parse(&apollo_meta)?)?.build()?;

    let mut configs = Vec::new();
    for apollo_namespace in apollo_namespaces {
        let apollo_configuration = apollo_client
            .cached_fetch(CachedFetchRequest {
                app_id: app_id.clone(),
                namespace_name: apollo_namespace.clone(),
                ..Default::default()
            })
            .await?;
        configs.push(apollo_configuration);
        //
    }

    Ok(configs)
}