pexels_api/collections/
items.rs

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