pexels_api/collections/
featured.rs

1use crate::{
2    CollectionsResponse, Pexels, PexelsError, PEXELS_API, PEXELS_COLLECTIONS_PATH, PEXELS_VERSION,
3};
4use url::Url;
5
6/// Path to get featured collections.
7const PEXELS_FEATURED_PATH: &str = "featured";
8
9/// Represents a request to fetch all featured collections from the Pexels API.
10pub struct Featured {
11    page: Option<usize>,
12    per_page: Option<usize>,
13}
14
15impl Featured {
16    /// Creates a new `FeaturedBuilder` for constructing a `Featured` request.
17    pub fn builder() -> FeaturedBuilder {
18        FeaturedBuilder::default()
19    }
20
21    /// Constructs the URI for the featured collections request based on the [`FeaturedBuilder`] builder's parameters.
22    pub fn create_uri(&self) -> crate::BuilderResult {
23        let uri = format!(
24            "{}/{}/{}/{}",
25            PEXELS_API, PEXELS_VERSION, PEXELS_COLLECTIONS_PATH, PEXELS_FEATURED_PATH
26        );
27
28        let mut url = Url::parse(uri.as_str())?;
29
30        if let Some(page) = &self.page {
31            url.query_pairs_mut().append_pair("page", page.to_string().as_str());
32        }
33
34        if let Some(per_page) = &self.per_page {
35            url.query_pairs_mut().append_pair("per_page", per_page.to_string().as_str());
36        }
37
38        Ok(url.into())
39    }
40
41    /// Fetches the featured collections data from the Pexels API.
42    pub async fn fetch(&self, client: &Pexels) -> Result<CollectionsResponse, PexelsError> {
43        let url = self.create_uri()?;
44        let response = client.make_request(url.as_str()).await?;
45        let collection_response: CollectionsResponse = serde_json::from_value(response)?;
46        Ok(collection_response)
47    }
48}
49
50/// Builder for constructing a `Featured` request.
51#[derive(Default)]
52pub struct FeaturedBuilder {
53    page: Option<usize>,
54    per_page: Option<usize>,
55}
56
57impl FeaturedBuilder {
58    /// Creates a new `FeaturedBuilder`.
59    pub fn new() -> Self {
60        Self { page: None, per_page: None }
61    }
62
63    /// Sets the page number for the featured collections request.
64    pub fn page(mut self, page: usize) -> Self {
65        self.page = Some(page);
66        self
67    }
68
69    /// Sets the number of results per page for the featured collections request.
70    pub fn per_page(mut self, per_page: usize) -> Self {
71        self.per_page = Some(per_page);
72        self
73    }
74
75    /// Build the `Featured` request from the `FeaturedBuilder` parameters.
76    pub fn build(self) -> Featured {
77        Featured { page: self.page, per_page: self.per_page }
78    }
79}