Skip to main content

trading_ig/
config.rs

1//! Configuration types: environments, base URLs, defaults.
2
3use std::time::Duration;
4
5use url::Url;
6
7/// IG API environment.
8///
9/// Demo accounts are free to create at <https://www.ig.com/uk/demo-account>.
10/// Use `Environment::Custom` only for testing against a mock server.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Environment {
13    Demo,
14    Live,
15    /// Override the base URL (e.g. a wiremock instance during tests).
16    Custom(Url),
17}
18
19impl Environment {
20    /// The canonical REST base URL for this environment.
21    pub fn base_url(&self) -> Url {
22        match self {
23            Environment::Demo => {
24                Url::parse("https://demo-api.ig.com/gateway/deal/").expect("static URL is valid")
25            }
26            Environment::Live => {
27                Url::parse("https://api.ig.com/gateway/deal/").expect("static URL is valid")
28            }
29            Environment::Custom(u) => {
30                let mut u = u.clone();
31                // Ensure trailing slash so `Url::join` behaves correctly.
32                if !u.path().ends_with('/') {
33                    let new_path = format!("{}/", u.path());
34                    u.set_path(&new_path);
35                }
36                u
37            }
38        }
39    }
40}
41
42/// Tunable client parameters. Most users won't need to touch this directly —
43/// configure via [`crate::IgClientBuilder`].
44#[derive(Debug, Clone)]
45pub struct IgConfig {
46    pub environment: Environment,
47    pub api_key: String,
48    pub user_agent: String,
49    pub request_timeout: Duration,
50    /// How early before the OAuth `expires_in` to proactively refresh.
51    pub token_refresh_skew: Duration,
52}
53
54impl IgConfig {
55    pub fn new(environment: Environment, api_key: impl Into<String>) -> Self {
56        Self {
57            environment,
58            api_key: api_key.into(),
59            user_agent: format!("trading-ig-rust/{}", env!("CARGO_PKG_VERSION")),
60            request_timeout: Duration::from_secs(30),
61            token_refresh_skew: Duration::from_secs(10),
62        }
63    }
64}