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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//! Price module that gives access to the [PriceApi] struct

use crate::{
    api::{client::HttpClient, url::TankerUrl},
    error, models,
    utils::price::format_ids_string,
};
use std::{fmt::Display, sync::Arc};

const MAX_REQUEST_STATION_IDS: usize = 10;

/// Struct that holds the current reqwest client of the library and gives access to the price api of
/// the tankerkoenig API.
///
/// ## Example
/// ```
/// use tankerkoenig::Tankerkoenig;
/// use tankerkoenig::models;
///
/// async fn request_station_prices() -> Result<models::PriceResponse, tankerkoenig::Error> {
///    let tanker = Tankerkoenig::new("your-api-key")?;
///    let prices = tanker.price.fetch(&[Some("station-id-1"), Some("station-id-2"), Some("station-id-3"), Some("station-id-4"), Some("station-id-5"), None, None, None, None, None]).await?;
///    Ok(prices)
/// }
/// ```
#[derive(Clone)]
pub struct PriceApi {
    client: Arc<Box<dyn HttpClient>>,
    api_key: String,
}

impl std::fmt::Debug for PriceApi {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PriceApi")
            .field("client", &self.client)
            .field("api_key", &"********")
            .finish()
    }
}

impl TankerUrl for PriceApi {}

impl PriceApi {
    pub(crate) fn new(client: Arc<Box<dyn HttpClient>>, api_key: String) -> Self {
        Self { client, api_key }
    }

    /// Fetch the prices of all fuel types of the given station ids (up to 10 at once).
    ///
    /// You can only fetch prices for 10 stations at once. If you want to fetch more than 10 stations,
    /// you have to call this function multiple times. This is due to a limitation of the
    /// [tankerkoenig API](https://creativecommons.tankerkoenig.de/). Use the helper [`macro@chunk_into_option_arrays`](crate::chunk_into_option_arrays) to make this easier.
    ///
    /// ## Example
    /// ```
    /// use tankerkoenig::Tankerkoenig;
    /// use tankerkoenig::models;
    ///
    /// async fn request_station_prices() -> Result<models::PriceResponse, tankerkoenig::Error> {
    ///    let tanker = Tankerkoenig::new("your-api-key")?;
    ///    let prices = tanker.price.fetch(&[Some("station-id-1"), Some("station-id-2"), Some("station-id-3"), Some("station-id-4"), Some("station-id-5"), None, None, None, None, None]).await?;
    ///    Ok(prices)
    /// }
    /// ```
    ///
    /// ## Example with [`macro@chunk_into_option_arrays`](crate::chunk_into_option_arrays)
    /// ```
    /// use tankerkoenig::Tankerkoenig;
    /// use tankerkoenig::models;
    /// use tankerkoenig::chunk_into_option_arrays;
    ///
    /// async fn request_station_prices() -> Result<Vec<models::PriceResponse>, tankerkoenig::Error> {
    ///   let tanker = Tankerkoenig::new("your-api-key")?;
    ///   let station_ids = ["id-1", "id-2", "id-3", "id-4", "id-5", "id-6", "id-7"];
    ///
    ///   let mut all_prices = Vec::new();
    ///   for chunk in chunk_into_option_arrays!(station_ids) {
    ///     let prices = tanker.price.fetch(&chunk).await?;
    ///    // Remember to wait between the requests to not get blocked by the API
    ///     all_prices.push(prices);
    ///   }
    ///   Ok(all_prices)
    /// }
    /// ```
    ///  
    pub async fn fetch<S>(
        &self,
        ids: &[Option<S>; MAX_REQUEST_STATION_IDS],
    ) -> Result<models::price::PriceResponse, error::TankerkoenigError>
    where
        S: AsRef<str> + Display,
    {
        let mut url = self.base_url(&self.api_key, Some("json/prices.php"))?;
        url.query_pairs_mut()
            .append_pair("ids", &format_ids_string(ids));
        let res_body = self.client.get(&url).await?;
        serde_json::from_str::<models::price::PriceResponse>(&res_body)
            .map_err(|_| error::TankerkoenigError::ResponseParsingError { body: res_body })
    }

    /// Fetch the prices of a single station
    ///
    /// ## Example
    /// ```
    /// use tankerkoenig::Tankerkoenig;
    /// use tankerkoenig::models;
    ///
    /// async fn request_single_station_prices() -> Result<models::PriceResponse, tankerkoenig::Error> {
    ///    let tanker = Tankerkoenig::new("your-api-key")?;
    ///    let station_prices = tanker.price.fetch_one("station-id").await?;
    ///    Ok(station_prices)
    /// }
    /// ```
    pub async fn fetch_one<S>(
        &self,
        id: S,
    ) -> Result<models::price::PriceResponse, error::TankerkoenigError>
    where
        S: AsRef<str> + Display,
    {
        let mut url = self.base_url(&self.api_key, Some("json/prices.php"))?;
        url.query_pairs_mut().append_pair("ids", id.as_ref());
        let res_body = self.client.get(&url).await?;
        serde_json::from_str::<models::price::PriceResponse>(&res_body)
            .map_err(|_| error::TankerkoenigError::ResponseParsingError { body: res_body })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::api::client::MockHttpClient;
    use futures::future::ready;
    use mockall::predicate::*;
    use std::pin::Pin;

    #[tokio::test]
    async fn should_fetch_station_price() {
        let data_string = std::fs::read_to_string("./test/data/prices.json").unwrap();
        let api_key = String::from("123");

        let mut mock_client = MockHttpClient::new();
        let closure_data_string = data_string.clone();
        mock_client
            .expect_get()
            .times(1)
            .with(eq(reqwest::Url::parse(
                "https://creativecommons.tankerkoenig.de/json/prices.php?apikey=123&ids=456",
            )
            .unwrap()))
            .returning(move |_| {
                let result = Ok(String::from(closure_data_string.clone()));
                Pin::from(Box::new(ready(result)))
            });

        let api = PriceApi::new(Arc::new(Box::new(mock_client)), api_key);
        let res = api.fetch_one("456").await.unwrap();

        let station_prices: models::price::PriceResponse =
            serde_json::from_str(&data_string).unwrap();

        assert_eq!(res, station_prices);
    }

    #[tokio::test]
    async fn should_fetch_station_prices() {
        let data_string = std::fs::read_to_string("./test/data/prices.json").unwrap();
        let api_key = String::from("123");

        let mut mock_client = MockHttpClient::new();
        let closure_data_string = data_string.clone();
        mock_client
            .expect_get()
            .times(1)
            .with(eq(reqwest::Url::parse(
                "https://creativecommons.tankerkoenig.de/json/prices.php?apikey=123&ids=456%2C789",
            )
            .unwrap()))
            .returning(move |_| {
                let result = Ok(String::from(closure_data_string.clone()));
                Pin::from(Box::new(ready(result)))
            });

        let ids = ["456", "789"];
        let transformed = crate::chunk_into_option_arrays!(ids);

        let api = PriceApi::new(Arc::new(Box::new(mock_client)), api_key);
        let res = api.fetch(&transformed.get(0).unwrap()).await.unwrap();

        let station_prices: models::price::PriceResponse =
            serde_json::from_str(&data_string).unwrap();

        assert_eq!(res, station_prices);
    }

    #[test]
    fn should_obfuscated_token_in_debug() {
        let api_key = String::from("123");
        let mock_client = MockHttpClient::new();

        let api = PriceApi::new(Arc::new(Box::new(mock_client)), api_key);

        assert_eq!(
            format!("{:?}", api),
            "PriceApi { client: MockHttpClient, api_key: \"********\" }"
        );
    }
}