carbone_sdk_rust/
config.rs

1pub const CARBONE_API_URL: &str = "https://api.carbone.io";
2pub const CARBONE_API_VERSION: &str = "4";
3
4use anyhow::{anyhow, Result};
5
6use validator::Validate;
7
8use crate::errors::CarboneError;
9use serde::Deserialize;
10use std::fs;
11use std::str::FromStr;
12
13use crate::types::ApiVersion;
14
15#[derive(Debug, Clone, Deserialize, Validate, PartialEq, Eq)]
16#[serde(rename_all = "camelCase")]
17pub struct Config {
18    #[validate(url)]
19    pub api_url: String,
20    pub api_timeout: u64,
21    pub api_version: ApiVersion,
22}
23
24impl Config {
25    /// Create a new Configuraiton.
26    pub fn new(api_url: String, api_timeout: u64, api_version: ApiVersion) -> Result<Self> {
27        let config = Self {
28            api_url,
29            api_timeout,
30            api_version,
31        };
32
33        config.validate()?;
34        Ok(config)
35    }
36
37    /// Load a Configuraiton from a file.
38    pub fn from_file(path: &str) -> Result<Self> {
39        let file_content =
40            fs::read_to_string(path).or(Err(CarboneError::FileNotFound(path.to_string())))?;
41        let config: Self = Self::from_str(file_content.as_str())?;
42        config.validate()?;
43        Ok(config)
44    }
45}
46
47/// Load a Default Configuraiton.
48impl Default for Config {
49    fn default() -> Self {
50        Self {
51            api_url: CARBONE_API_URL.to_string(),
52            api_timeout: 60,
53            api_version: ApiVersion::new(CARBONE_API_VERSION.to_string()).unwrap(),
54        }
55    }
56}
57
58/// Load a Configuraiton from a str.
59///
60/// This function will create new Config struct with,
61/// the values from the str given.
62///
63/// # Example
64///
65/// ```no_run
66///
67/// use std::str::FromStr;
68/// use carbone_sdk_rust::config::Config;
69/// use carbone_sdk_rust::errors::CarboneError;
70///
71/// fn main() -> Result<(), CarboneError> {
72///     
73///     let config = Config::from_str(r#"{
74///         "apiUrl": "http://127.0.0.1",
75///         "apiTimeout": 4,
76///         "apiVersion" : "4"
77///     }"#)?;
78///
79///     Ok(())
80/// }
81/// ```
82impl FromStr for Config {
83    type Err = anyhow::Error;
84
85    fn from_str(s: &str) -> Result<Self> {
86        match serde_json::from_str(s) {
87            Ok(config) => Ok(config),
88            Err(e) => Err(anyhow!(format!(
89                "CarboneSDK FromStr JsonParseError: {}",
90                e.to_string()
91            ))),
92        }
93    }
94}