1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use models::response::{DiscoveryPagedData, DiscoveryPagedResponse, DiscoveryResponse};
use reqwest::Client;
use serde::de::DeserializeOwned;

pub mod error;
mod event;
pub mod models;
pub(crate) mod request_builder;

pub struct Discovery {
    api_key: String,
    client: Client,
}

impl Discovery {
    const URL: &'static str = "https://app.ticketmaster.com/discovery/v2";
    pub(crate) async fn call_paged_request<R: DeserializeOwned>(
        &self,
        endpoint: &str,
        args: String,
    ) -> error::Result<DiscoveryPagedData<R>> {
        let args = if args.is_empty() {
            String::new()
        } else {
            format!("&{args}")
        };
        let raw_response = self
            .client
            .get(format!(
                "{}{endpoint}?apikey={}{args}",
                Self::URL,
                self.api_key
            ))
            .send()
            .await?
            .text()
            .await?;

        if let Ok(data) = serde_json::from_str::<DiscoveryPagedResponse<R>>(&raw_response) {
            data.into_result()
        } else {
            tracing::info!("{raw_response}");
            let data: DiscoveryPagedData<R> = serde_json::from_str(&raw_response)?;
            Ok(data)
        }
    }

    pub(crate) async fn call_request<R: DeserializeOwned>(
        &self,
        endpoint: &str,
        args: String,
    ) -> error::Result<R> {
        let args = if args.is_empty() {
            String::new()
        } else {
            format!("&{args}")
        };
        let raw_response = self
            .client
            .get(format!(
                "{}{endpoint}?apikey={}{args}",
                Self::URL,
                self.api_key
            ))
            .send()
            .await?
            .text()
            .await?;

        if let Ok(data) = serde_json::from_str::<DiscoveryResponse<R>>(&raw_response) {
            data.into_result()
        } else {
            tracing::info!("{raw_response}");
            let data: R = serde_json::from_str(&raw_response)?;
            Ok(data)
        }
    }

    pub fn from_env(env_key: &str) -> Result<Self, std::env::VarError> {
        Ok(Self::new(std::env::var(env_key)?))
    }

    pub fn new(api_key: impl ToString) -> Self {
        Self {
            api_key: api_key.to_string(),
            client: Default::default(),
        }
    }

    pub fn with_client(mut self, client: Client) -> Self {
        self.client = client;
        self
    }
}