pexels_api/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 =
20            format!("{}/{}/{}/{}", PEXELS_API, PEXELS_VIDEO_PATH, PEXELS_GET_VIDEO_PATH, self.id);
21
22        let url = Url::parse(uri.as_str())?;
23
24        Ok(url.into())
25    }
26
27    /// Fetches the video data from the Pexels API.
28    pub async fn fetch(&self, client: &Pexels) -> Result<Video, PexelsError> {
29        let url = self.create_uri()?;
30        let response = client.make_request(url.as_str()).await?;
31        let video: Video = serde_json::from_value(response)?;
32        Ok(video)
33    }
34}
35
36/// Builder for `FetchVideo`.
37#[derive(Default)]
38pub struct FetchVideoBuilder {
39    id: usize,
40}
41
42impl FetchVideoBuilder {
43    /// Creates a new `FetchVideoBuilder`.
44    pub fn new() -> Self {
45        Self { id: 0 }
46    }
47
48    /// Sets the ID of the video to be fetched.
49    pub fn id(mut self, id: usize) -> Self {
50        self.id = id;
51        self
52    }
53
54    /// Builds a `FetchVideo` instance from the `FetchVideoBuilder`.
55    pub fn build(self) -> FetchVideo {
56        FetchVideo { id: self.id }
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn test_id() {
66        let uri = FetchVideoBuilder::new().id(123).build();
67        assert_eq!("https://api.pexels.com/videos/videos/123", uri.create_uri().unwrap());
68    }
69}