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
use serde::de::DeserializeOwned;

use super::model::{GiphyRequest, API_ROOT};

/// Implementation of Giphy API that uses synchronous [`reqwest::Client`]
///
/// [`reqwest::Client`]: https://docs.rs/reqwest/0.11.4/reqwest/blocking/struct.Client.html
pub struct SyncApi {
    url: String,
    key: String,
    client: reqwest::blocking::Client,
}

impl SyncApi {
    /// Creates a new synchronous Giphy API Client
    pub fn new(key: String, client: reqwest::blocking::Client) -> SyncApi {
        SyncApi {
            url: API_ROOT.to_string(),
            key,
            client,
        }
    }

    pub fn new_with_url(url: String, key: String, client: reqwest::blocking::Client) -> SyncApi {
        SyncApi { url, key, client }
    }
}

pub trait RunnableSyncRequest<ResponseType> {
    /// Sends a request to a [SyncApi]
    ///
    /// [SyncApi]: ./struct.SyncApi.html
    fn send_to(&self, api: &SyncApi) -> Result<ResponseType, reqwest::Error>;
}

impl<'a, RequestType, ResponseType> RunnableSyncRequest<ResponseType> for RequestType
where
    RequestType: GiphyRequest<ResponseType>,
    ResponseType: DeserializeOwned,
{
    fn send_to(&self, api: &SyncApi) -> Result<ResponseType, reqwest::Error> {
        let endpoint = format!("{}/{}", api.url, self.get_endpoint());

        let response = api
            .client
            .get(&endpoint)
            .query(&[("api_key", api.key.clone())])
            .query(&self)
            .send()?;

        let response_data = response.error_for_status()?.json::<ResponseType>()?;

        Ok(response_data)
    }
}

#[cfg(test)]
mod test {
    use dotenv::dotenv;
    use mockito::{mock, server_url, Matcher};
    use std::env;

    use super::*;
    use crate::v1;

    #[test]
    fn api_search_200_ok() {
        dotenv().ok();
        let api_key = env::var("GIPHY_API_KEY_TEST")
            .unwrap_or_else(|e| panic!("Error retrieving env variable: {:?}", e));
        let api_root = server_url();
        let _m = mock(
            "GET",
            Matcher::Regex(r"/gifs/search.*api_key=.+q=.+".to_string()),
        )
        .with_status(200)
        .with_body_from_file("data/example-search-response.json")
        .create();

        let client = reqwest::blocking::Client::new();
        let api = SyncApi::new_with_url(api_root, api_key, client);

        let response = v1::gifs::SearchRequest::new("rage")
            .send_to(&api)
            .unwrap_or_else(|e| panic!("Error while calling search endpoint: {:?}", e));

        assert!(response.pagination.count > 0);
    }

    #[test]
    fn api_trending_200_ok() {
        dotenv().ok();
        let api_key = env::var("GIPHY_API_KEY_TEST")
            .unwrap_or_else(|e| panic!("Error retrieving env variable: {:?}", e));
        let api_root = server_url();
        let _m = mock(
            "GET",
            Matcher::Regex(r"/gifs/trending.*api_key=.+".to_string()),
        )
        .with_status(200)
        .with_body_from_file("data/example-trending-response.json")
        .create();

        let client = reqwest::blocking::Client::new();
        let api = SyncApi::new_with_url(api_root, api_key, client);

        let response = v1::gifs::TrendingRequest::new()
            .send_to(&api)
            .unwrap_or_else(|e| panic!("Error while calling search endpoint: {:?}", e));

        assert!(response.pagination.count > 0);
    }

    #[test]
    fn api_translate_200_ok() {
        dotenv().ok();
        let api_key = env::var("GIPHY_API_KEY_TEST")
            .unwrap_or_else(|e| panic!("Error retrieving env variable: {:?}", e));
        let api_root = server_url();
        let _m = mock(
            "GET",
            Matcher::Regex(r"/gifs/translate.*api_key=.+&s=.+".to_string()),
        )
        .with_status(200)
        .with_body_from_file("data/example-translate-response.json")
        .create();

        let client = reqwest::blocking::Client::new();
        let api = SyncApi::new_with_url(api_root, api_key, client);

        let response = v1::gifs::TranslateRequest::new("rage")
            .send_to(&api)
            .unwrap_or_else(|e| panic!("Error while calling search endpoint: {:?}", e));

        assert!(response.meta.status == 200);
    }

    #[test]
    fn api_random_200_ok() {
        dotenv().ok();
        let api_key = env::var("GIPHY_API_KEY_TEST")
            .unwrap_or_else(|e| panic!("Error retrieving env variable: {:?}", e));
        let api_root = server_url();
        let _m = mock(
            "GET",
            Matcher::Regex(r"/gifs/random.*api_key=.+".to_string()),
        )
        .with_status(200)
        .with_body_from_file("data/example-random-response.json")
        .create();

        let client = reqwest::blocking::Client::new();
        let api = SyncApi::new_with_url(api_root, api_key, client);

        let response = v1::gifs::RandomRequest::new()
            .send_to(&api)
            .unwrap_or_else(|e| panic!("Error while calling search endpoint: {:?}", e));

        assert!(response.meta.status == 200);
    }

    #[test]
    fn api_get_gif_200_ok() {
        dotenv().ok();
        let api_key = env::var("GIPHY_API_KEY_TEST")
            .unwrap_or_else(|e| panic!("Error retrieving env variable: {:?}", e));
        let api_root = server_url();
        let _m = mock(
            "GET",
            Matcher::Regex(r"/gifs/xT4uQulxzV39haRFjG.*api_key=.+".to_string()),
        )
        .with_status(200)
        .with_body_from_file("data/example-get-gif-response.json")
        .create();

        let client = reqwest::blocking::Client::new();
        let api = SyncApi::new_with_url(api_root, api_key, client);

        let response = v1::gifs::GetGifRequest::new("xT4uQulxzV39haRFjG")
            .send_to(&api)
            .unwrap_or_else(|e| panic!("Error while calling search endpoint: {:?}", e));

        assert!(response.meta.status == 200);
    }

    #[test]
    fn api_get_gifs_200_ok() {
        dotenv().ok();
        let api_key = env::var("GIPHY_API_KEY_TEST")
            .unwrap_or_else(|e| panic!("Error retrieving env variable: {:?}", e));
        let api_root = server_url();
        let _m = mock(
            "GET",
            Matcher::Regex(r"/gifs.*api_key=.+ids=.+".to_string()),
        )
        .with_status(200)
        .with_body_from_file("data/example-get-gifs-response.json")
        .create();

        let client = reqwest::blocking::Client::new();
        let api = SyncApi::new_with_url(api_root, api_key, client);

        let response =
            v1::gifs::GetGifsRequest::new(vec!["xT4uQulxzV39haRFjG", "3og0IPxMM0erATueVW"])
                .send_to(&api)
                .unwrap_or_else(|e| panic!("Error while calling search endpoint: {:?}", e));

        assert!(response.meta.status == 200);
    }
}