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