amazon_spapi/client/
config.rs

1use anyhow::Result;
2use serde::{Deserialize, Serialize};
3use std::fs;
4
5#[derive(Debug, Serialize, Deserialize, Clone)]
6pub struct SpapiConfig {
7    pub client_id: String,
8    pub client_secret: String,
9    pub refresh_token: String,
10    pub marketplace_id: String,
11    pub region: String,
12    pub sandbox: bool,
13    pub user_agent: Option<String>,
14    pub timeout_sec: Option<u64>,
15    pub rate_limit_factor: Option<f64>,
16}
17
18impl SpapiConfig {
19    pub fn from_env() -> Result<Self> {
20        let client_id = std::env::var("SPAPI_CLIENT_ID").map_err(|_| {
21            anyhow::anyhow!("SPAPI_CLIENT_ID environment variable is not set")
22        })?;
23        let client_secret = std::env::var("SPAPI_CLIENT_SECRET").map_err(|_| {
24            anyhow::anyhow!("SPAPI_CLIENT_SECRET environment variable is not set")
25        })?;
26        let refresh_token = std::env::var("SPAPI_REFRESH_TOKEN").map_err(|_| {
27            anyhow::anyhow!("SPAPI_REFRESH_TOKEN environment variable is not set")
28        })?;
29        let marketplace_id = std::env::var("SPAPI_MARKETPLACE_ID").map_err(|_| {
30            anyhow::anyhow!("SPAPI_MARKETPLACE_ID environment variable is not set")
31        })?;
32        let region = std::env::var("SPAPI_REGION").map_err(|_| {
33            anyhow::anyhow!("SPAPI_REGION environment variable is not set")
34        })?;
35        let sandbox = std::env::var("SPAPI_SANDBOX").map_err(|_| {
36            anyhow::anyhow!("SPAPI_SANDBOX environment variable is not set or invalid")
37        })?;
38        let sandbox = sandbox == "true" || sandbox == "1";
39        Ok(Self {
40            client_id,
41            client_secret,
42            refresh_token,
43            marketplace_id,
44            region,
45            sandbox,
46            user_agent: None,
47            timeout_sec: Some(30),
48            rate_limit_factor: None,
49        })
50    }
51}
52
53#[derive(Debug, Serialize, Deserialize)]
54pub struct Config {
55    pub spapi: SpapiConfig,
56}
57
58impl Config {
59    pub fn from_file(path: &str) -> Result<Self> {
60        let content = fs::read_to_string(path)?;
61        let config: Config = toml::from_str(&content)?;
62        Ok(config)
63    }
64
65    pub fn from_default_file() -> Result<Self> {
66        Self::from_file("config.toml")
67    }
68}