pexels_api/photos/
search.rs

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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use crate::{
    Locale, Orientation, Pexels, PexelsError, PhotosResponse, Size, PEXELS_API, PEXELS_VERSION,
};
use url::Url;
const PEXELS_PHOTO_SEARCH_PATH: &str = "search";

/// Represents a hexadecimal color code.
/// Used as an input value for [`Color::Hex`] when specifying a hexadecimal color code.
///
/// #Example
///
/// ```
/// use pexels_api::{Color, Hex, SearchBuilder};
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///        let hex_color = Hex::from_borrowed_str("#FFFFFF")?;
///        let uri = SearchBuilder::new().color(Color::Hex(hex_color)).build();
///        assert_eq!(
///            "https://api.pexels.com/v1/search?query=&color=%23FFFFFF",
///            uri.create_uri()?
///        );
///        Ok(())
///  }
/// ```
///
/// # Errors
/// Returns [`PexelsError::HexColorCodeError`] if the string is not a valid hexadecimal color code.
#[derive(Debug, PartialEq)]
pub struct Hex<'a>(&'a str);

impl<'a> Hex<'a> {
    /// Create a new [`Hex`] from a string literal.
    #[allow(clippy::should_implement_trait)]
    pub fn from_borrowed_str(v: &'a str) -> Result<Self, PexelsError> {
        if v.len() != 7 {
            return Err(PexelsError::HexColorCodeError(format!("{} is not 7 characters long.", v)));
        }

        if !v.starts_with("#") {
            return Err(PexelsError::HexColorCodeError(format!("{} does not start with #.", v)));
        }

        // 检查是否为有效的 ASCII 字符
        if !v[1..].chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(PexelsError::HexColorCodeError(format!(
                "{} have values that are not valid ASCII punctuation character.",
                v
            )));
        }

        Ok(Self(v))
    }
}

/// Represents the desired photo color.
pub enum Color<'a> {
    Red,
    Orange,
    Yellow,
    Green,
    Turquoise,
    Blue,
    Violet,
    Pink,
    Brown,
    Black,
    Gray,
    White,
    Hex(Hex<'a>),
}

impl Color<'_> {
    /// Returns the string representation of the color.
    fn as_str(&self) -> Result<&str, PexelsError> {
        let value = match self {
            Color::Red => "red",
            Color::Orange => "orange",
            Color::Yellow => "yellow",
            Color::Green => "green",
            Color::Turquoise => "turquoise",
            Color::Blue => "blue",
            Color::Violet => "violet",
            Color::Pink => "pink",
            Color::Brown => "brown",
            Color::Black => "black",
            Color::Gray => "gray",
            Color::White => "white",
            Color::Hex(v) => v.0,
        };

        Ok(value)
    }
}

/// Represents a search query to the Pexels API.
pub struct Search<'a> {
    query: &'a str,
    page: Option<usize>,
    per_page: Option<usize>,
    orientation: Option<Orientation>,
    size: Option<Size>,
    color: Option<Color<'a>>,
    locale: Option<Locale>,
}

impl<'a> Search<'a> {
    /// Creates a new [`SearchBuilder`] for building URI's.
    pub fn builder() -> SearchBuilder<'a> {
        SearchBuilder::default()
    }

    /// Creates a URI from the search parameters. [`SearchBuilder`].
    pub fn create_uri(&self) -> crate::BuilderResult {
        let uri = format!("{}/{}/{}", PEXELS_API, PEXELS_VERSION, PEXELS_PHOTO_SEARCH_PATH);

        let mut url = Url::parse(uri.as_str())?;
        url.query_pairs_mut().append_pair("query", self.query);

        if let Some(page) = &self.page {
            url.query_pairs_mut().append_pair("page", page.to_string().as_str());
        }

        if let Some(per_page) = &self.per_page {
            url.query_pairs_mut().append_pair("per_page", per_page.to_string().as_str());
        }

        if let Some(orientation) = &self.orientation {
            url.query_pairs_mut().append_pair("orientation", orientation.as_str());
        }

        if let Some(size) = &self.size {
            url.query_pairs_mut().append_pair("size", size.as_str());
        }

        if let Some(color) = &self.color {
            url.query_pairs_mut().append_pair("color", color.as_str()?);
        }

        if let Some(locale) = &self.locale {
            url.query_pairs_mut().append_pair("locale", locale.as_str());
        }

        Ok(url.into())
    }

    /// Fetches the list of photos from the Pexels API based on the search parameters.
    pub async fn fetch(&self, client: &Pexels) -> Result<PhotosResponse, PexelsError> {
        let url = self.create_uri()?;
        let response = client.make_request(url.as_str()).await?;
        let photos_response: PhotosResponse = serde_json::from_value(response)?;
        Ok(photos_response)
    }
}

/// Builder for [`Search`].
#[derive(Default)]
pub struct SearchBuilder<'a> {
    query: &'a str,
    page: Option<usize>,
    per_page: Option<usize>,
    orientation: Option<Orientation>,
    size: Option<Size>,
    color: Option<Color<'a>>,
    locale: Option<Locale>,
}

impl<'a> SearchBuilder<'a> {
    /// Creates a new [`SearchBuilder`].
    pub fn new() -> Self {
        Self {
            query: "",
            page: None,
            per_page: None,
            orientation: None,
            size: None,
            color: None,
            locale: None,
        }
    }

    /// Sets the search query.
    pub fn query(mut self, query: &'a str) -> Self {
        self.query = query;
        self
    }

    /// Sets the page number for the request.
    pub fn page(mut self, page: usize) -> Self {
        self.page = Some(page);
        self
    }

    /// Sets the number of results per page for the request.
    pub fn per_page(mut self, per_page: usize) -> Self {
        self.per_page = Some(per_page);
        self
    }

    /// Sets the desired photo orientation.
    pub fn orientation(mut self, orientation: Orientation) -> Self {
        self.orientation = Some(orientation);
        self
    }

    /// Sets the minimum photo size.
    pub fn size(mut self, size: Size) -> Self {
        self.size = Some(size);
        self
    }

    /// Sets the desired photo color.
    pub fn color(mut self, color: Color<'a>) -> Self {
        self.color = Some(color);
        self
    }

    /// Sets the locale of the search.
    pub fn locale(mut self, locale: Locale) -> Self {
        self.locale = Some(locale);
        self
    }

    /// Builds a `Search` instance from the `SearchBuilder`
    pub fn build(self) -> Search<'a> {
        Search {
            query: self.query,
            page: self.page,
            per_page: self.per_page,
            orientation: self.orientation,
            size: self.size,
            color: self.color,
            locale: self.locale,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_query() {
        let uri = SearchBuilder::new().query("bar").build();
        assert_eq!("https://api.pexels.com/v1/search?query=bar", uri.create_uri().unwrap());
    }

    #[test]
    fn test_page() {
        let uri = SearchBuilder::new().page(1).build();
        assert_eq!("https://api.pexels.com/v1/search?query=&page=1", uri.create_uri().unwrap());
    }

    #[test]
    fn test_per_page() {
        let uri = SearchBuilder::new().per_page(1).build();
        assert_eq!("https://api.pexels.com/v1/search?query=&per_page=1", uri.create_uri().unwrap());
    }

    #[test]
    fn test_orientation() {
        let uri = SearchBuilder::new().orientation(Orientation::Landscape).build();
        assert_eq!(
            "https://api.pexels.com/v1/search?query=&orientation=landscape",
            uri.create_uri().unwrap()
        );
    }

    #[test]
    fn test_size() {
        let uri = SearchBuilder::new().size(Size::Small).build();
        assert_eq!("https://api.pexels.com/v1/search?query=&size=small", uri.create_uri().unwrap());
    }

    #[test]
    fn test_color() {
        let uri = SearchBuilder::new().color(Color::Pink).build();
        assert_eq!("https://api.pexels.com/v1/search?query=&color=pink", uri.create_uri().unwrap());
    }

    #[test]
    fn test_hex_color_code() {
        let hex_color = Hex::from_borrowed_str("#FFFFFF").unwrap();
        let uri = SearchBuilder::new().color(Color::Hex(hex_color)).build();
        assert_eq!(
            "https://api.pexels.com/v1/search?query=&color=%23FFFFFF",
            uri.create_uri().unwrap()
        );
    }

    #[test]
    fn test_locale() {
        let uri = SearchBuilder::new().locale(Locale::sv_SE).build();
        assert_eq!(
            "https://api.pexels.com/v1/search?query=&locale=sv-SE",
            uri.create_uri().unwrap()
        );
    }

    #[test]
    fn test_hex_struct_length() {
        let hex_color = Hex::from_borrowed_str("#allanballan");
        assert_eq!(
            hex_color,
            Err(PexelsError::HexColorCodeError(String::from(
                "#allanballan is not 7 characters long."
            )))
        );
    }

    #[test]
    fn test_hex_struct_box_validation() {
        let hex_color = Hex::from_borrowed_str("FFFFFFF");
        assert_eq!(
            hex_color,
            Err(PexelsError::HexColorCodeError(String::from("FFFFFFF does not start with #.")))
        );
    }

    #[test]
    fn test_hex_struct_ascii_validation() {
        let hex_color = Hex::from_borrowed_str("#??????");
        assert_eq!(
            hex_color,
            Err(PexelsError::HexColorCodeError(String::from(
                "#?????? have values that are not valid ASCII punctuation character."
            )))
        );
    }
}