pexels_sdk/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            "{PEXELS_API}/{PEXELS_VERSION}/{PEXELS_COLLECTIONS_PATH}/{PEXELS_FEATURED_PATH}"
25        );
26
27        let mut url = Url::parse(uri.as_str())?;
28
29        if let Some(page) = &self.page {
30            url.query_pairs_mut()
31                .append_pair("page", page.to_string().as_str());
32        }
33
34        if let Some(per_page) = &self.per_page {
35            url.query_pairs_mut()
36                .append_pair("per_page", per_page.to_string().as_str());
37        }
38
39        Ok(url.into())
40    }
41
42    /// Fetches the featured collections data from the Pexels API.
43    pub async fn fetch(&self, client: &Pexels) -> Result<CollectionsResponse, PexelsError> {
44        let url = self.create_uri()?;
45        let response = client.make_request(url.as_str()).await?;
46        let collection_response: CollectionsResponse = serde_json::from_value(response)?;
47        Ok(collection_response)
48    }
49}
50
51/// Builder for constructing a `Featured` request.
52#[derive(Default)]
53pub struct FeaturedBuilder {
54    page: Option<usize>,
55    per_page: Option<usize>,
56}
57
58impl FeaturedBuilder {
59    /// Creates a new `FeaturedBuilder`.
60    pub fn new() -> Self {
61        Self {
62            page: None,
63            per_page: None,
64        }
65    }
66
67    /// Sets the page number for the featured collections request.
68    pub fn page(mut self, page: usize) -> Self {
69        self.page = Some(page);
70        self
71    }
72
73    /// Sets the number of results per page for the featured collections request.
74    pub fn per_page(mut self, per_page: usize) -> Self {
75        self.per_page = Some(per_page);
76        self
77    }
78
79    /// Build the `Featured` request from the `FeaturedBuilder` parameters.
80    pub fn build(self) -> Featured {
81        Featured {
82            page: self.page,
83            per_page: self.per_page,
84        }
85    }
86}