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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//! Station module that gives access to the [StationApi] struct
use crate::{
    api::{client::HttpClient, url::TankerUrl},
    error, models,
};
use std::sync::Arc;

/// Struct that holds the current reqwest client of the library and gives access to the station api of
/// the tankerkoenig API.
#[derive(Clone)]
pub struct StationApi {
    client: Arc<Box<dyn HttpClient>>,
    api_key: String,
}

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

impl TankerUrl for StationApi {}

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

    /// Fetch all stations near a given area with some basic informations
    ///
    /// ## Example
    /// ```
    /// use tankerkoenig::Tankerkoenig;
    /// use tankerkoenig::models;
    ///
    /// async fn request_near_stations() -> Result<models::AreaNearResponse, tankerkoenig::Error> {
    ///    let tanker = Tankerkoenig::new("your-api-key")?;
    ///    let latitude: f64 = 52.52;
    ///    let longitude: f64 = 13.40;
    ///    let radius: f64 = 10.0;
    ///    let near_stations_res = tanker.station.fetch_near(latitude, longitude, radius).await?;
    ///    Ok(near_stations_res)
    /// }
    /// ```
    pub async fn fetch_near(
        &self,
        lat: f64,
        lng: f64,
        radius: f64,
    ) -> Result<models::station::AreaNearResponse, error::TankerkoenigError> {
        let mut url = self.base_url(&self.api_key, Some("json/list.php"))?;
        url.query_pairs_mut()
            .append_pair("lat", &lat.to_string())
            .append_pair("lng", &lng.to_string())
            .append_pair("rad", &radius.to_string())
            .append_pair("type", "all");
        let res_body = self.client.get(&url).await?;
        serde_json::from_str::<models::station::AreaNearResponse>(&res_body)
            .map_err(|_| error::TankerkoenigError::ResponseParsingError { body: res_body })
    }

    /// Fetch all stations in a radius around the given coordinates that sell a specific kind
    /// of [Fuel](models::Fuel) and [sort](models::Sort) them in a certain order.
    ///
    /// ## Example
    /// ```
    /// use tankerkoenig::Tankerkoenig;
    /// use tankerkoenig::models;
    ///
    /// async fn request_fuel_near() -> Result<models::AreaFuelResponse, tankerkoenig::Error> {
    ///    let tanker = Tankerkoenig::new("your-api-key")?;
    ///    let latitude: f64 = 52.52;
    ///    let longitude: f64 = 13.40;
    ///    let radius: f64 = 10.0;
    ///    let fuel = models::Fuel::Diesel;
    ///    let sorting = models::Sort::Distance;
    ///    let stations = tanker.station.fetch_by_fuel(latitude, longitude, radius, fuel, sorting).await?;
    ///    Ok(stations)
    /// }
    /// ```
    pub async fn fetch_by_fuel(
        &self,
        lat: f64,
        lng: f64,
        radius: f64,
        fuel: models::Fuel,
        sort: models::Sort,
    ) -> Result<models::station::AreaFuelResponse, error::TankerkoenigError> {
        let mut url = self.base_url(&self.api_key, Some("json/list.php"))?;
        url.query_pairs_mut()
            .append_pair("lat", &lat.to_string())
            .append_pair("lng", &lng.to_string())
            .append_pair("rad", &radius.to_string())
            .append_pair("type", &fuel.to_string())
            .append_pair("sort", &sort.to_string());
        let res_body = self.client.get(&url).await?;
        serde_json::from_str::<models::station::AreaFuelResponse>(&res_body)
            .map_err(|_| error::TankerkoenigError::ResponseParsingError { body: res_body })
    }

    /// Fetch informations about a certain station by id.
    ///
    /// ## Example
    /// ```
    /// use tankerkoenig::Tankerkoenig;
    /// use tankerkoenig::models;
    ///
    /// async fn request_station() -> Result<models::DetailsResponse, tankerkoenig::Error> {
    ///    let tanker = Tankerkoenig::new("your-api-key")?;
    ///    let station_details = tanker.station.fetch_details("<station_id>").await?;
    ///    Ok(station_details)
    /// }
    /// ```
    pub async fn fetch_details<S: AsRef<str>>(
        &self,
        id: S,
    ) -> Result<models::station::DetailsResponse, error::TankerkoenigError> {
        let id = id.as_ref();
        let mut url = self.base_url(&self.api_key, Some("json/detail.php"))?;
        url.query_pairs_mut().append_pair("id", id);
        let res_body = self.client.get(&url).await?;
        serde_json::from_str::<models::station::DetailsResponse>(&res_body)
            .map_err(|_| error::TankerkoenigError::ResponseParsingError { body: res_body })
    }
}

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

    #[tokio::test]
    async fn should_fetch_near_stations() {
        let data_string = std::fs::read_to_string("./test/data/list_near.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/list.php?apikey=123&lat=52.52&lng=13.4&rad=10&type=all").unwrap()))
            .returning(move |_| {
                let result = Ok(String::from(closure_data_string.clone()));
                Pin::from(Box::new(ready(result)))
            });

        let api = StationApi::new(Arc::new(Box::new(mock_client)), api_key);
        let res = api.fetch_near(52.52, 13.40, 10.0).await.unwrap();

        let station_response: AreaNearResponse =
            serde_json::from_str(&data_string.clone()).unwrap();

        assert_eq!(res, station_response);
    }

    #[tokio::test]
    async fn should_fetch_stations_by_fuel() {
        let data_string = std::fs::read_to_string("./test/data/list.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/list.php?apikey=123&lat=52.52&lng=13.4&rad=10&type=diesel&sort=dist").unwrap()))
            .returning(move |_| {
                let result = Ok(String::from(closure_data_string.clone()));
                Pin::from(Box::new(ready(result)))
            });

        let api = StationApi::new(Arc::new(Box::new(mock_client)), api_key);
        let res = api
            .fetch_by_fuel(
                52.52,
                13.40,
                10.0,
                models::Fuel::Diesel,
                models::Sort::Distance,
            )
            .await
            .unwrap();

        let station_response: AreaFuelResponse =
            serde_json::from_str(&data_string.clone()).unwrap();

        assert_eq!(res, station_response);
    }

    #[tokio::test]
    async fn should_fetch_station_details() {
        let data_string = std::fs::read_to_string("./test/data/detail.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/detail.php?apikey=123&id=123",
            )
            .unwrap()))
            .returning(move |_| {
                let result = Ok(String::from(closure_data_string.clone()));
                Pin::from(Box::new(ready(result)))
            });

        let api = StationApi::new(Arc::new(Box::new(mock_client)), api_key);
        let res = api.fetch_details("123").await.unwrap();

        let station_response: models::station::DetailsResponse =
            serde_json::from_str(&data_string.clone()).unwrap();

        assert_eq!(res, station_response);
    }

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

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

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