carbone_sdk_rust/
config.rs1pub 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 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 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
47impl 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
58impl 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}