pexels_sdk/videos/
video.rs

1use crate::{Pexels, PexelsError, Video, PEXELS_API, PEXELS_VIDEO_PATH};
2use url::Url;
3/// Path to get a specific video.
4const PEXELS_GET_VIDEO_PATH: &str = "videos";
5
6/// Represents a request to fetch a specific video by its ID from the Pexels API.
7pub struct FetchVideo {
8    id: usize,
9}
10
11impl FetchVideo {
12    /// Creates a new `FetchVideoBuilder` for building URIs.
13    pub fn builder() -> FetchVideoBuilder {
14        FetchVideoBuilder::default()
15    }
16
17    /// Creates a URI from the provided values.
18    pub fn create_uri(&self) -> crate::BuilderResult {
19        let uri = format!(
20            "{}/{}/{}/{}",
21            PEXELS_API, PEXELS_VIDEO_PATH, PEXELS_GET_VIDEO_PATH, self.id
22        );
23
24        let url = Url::parse(uri.as_str())?;
25
26        Ok(url.into())
27    }
28
29    /// Fetches the video data from the Pexels API.
30    pub async fn fetch(&self, client: &Pexels) -> Result<Video, PexelsError> {
31        let url = self.create_uri()?;
32        let response = client.make_request(url.as_str()).await?;
33        let video: Video = serde_json::from_value(response)?;
34        Ok(video)
35    }
36}
37
38/// Builder for `FetchVideo`.
39#[derive(Default)]
40pub struct FetchVideoBuilder {
41    id: usize,
42}
43
44impl FetchVideoBuilder {
45    /// Creates a new `FetchVideoBuilder`.
46    pub fn new() -> Self {
47        Self { id: 0 }
48    }
49
50    /// Sets the ID of the video to be fetched.
51    pub fn id(mut self, id: usize) -> Self {
52        self.id = id;
53        self
54    }
55
56    /// Builds a `FetchVideo` instance from the `FetchVideoBuilder`.
57    pub fn build(self) -> FetchVideo {
58        FetchVideo { id: self.id }
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_id() {
68        let uri = FetchVideoBuilder::new().id(123).build();
69        assert_eq!(
70            "https://api.pexels.com/videos/videos/123",
71            uri.create_uri().unwrap()
72        );
73    }
74}