Skip to main content

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