pexels_sdk/photos/
photo.rs1use crate::{Pexels, PexelsError, Photo, PEXELS_API, PEXELS_VERSION};
2use url::Url;
3
4const PEXELS_GET_PHOTO_PATH: &str = "photos";
6
7pub struct FetchPhoto {
9 id: usize,
10}
11
12impl FetchPhoto {
13 pub fn builder() -> FetchPhotoBuilder {
15 FetchPhotoBuilder::default()
16 }
17
18 pub fn create_uri(&self) -> crate::BuilderResult {
20 let uri = format!(
21 "{}/{}/{}/{}",
22 PEXELS_API, PEXELS_VERSION, PEXELS_GET_PHOTO_PATH, self.id
23 );
24
25 let url = Url::parse(uri.as_str())?;
26
27 Ok(url.into())
28 }
29
30 pub async fn fetch(&self, client: &Pexels) -> Result<Photo, PexelsError> {
32 let url = self.create_uri()?;
33 let response = client.make_request(url.as_str()).await?;
34 let photo: Photo = serde_json::from_value(response)?;
35 Ok(photo)
36 }
37}
38
39#[derive(Default)]
41pub struct FetchPhotoBuilder {
42 id: usize,
43}
44
45impl FetchPhotoBuilder {
46 pub fn new() -> Self {
48 Self { id: 0 }
49 }
50
51 pub fn id(mut self, id: usize) -> Self {
53 self.id = id;
54 self
55 }
56
57 pub fn build(self) -> FetchPhoto {
59 FetchPhoto { id: self.id }
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66 use dotenvy::dotenv;
67 use std::env;
68
69 #[test]
70 fn test_id() {
71 let uri = FetchPhotoBuilder::new().id(123).build();
72 assert_eq!(
73 "https://api.pexels.com/v1/photos/123",
74 uri.create_uri().unwrap()
75 );
76 }
77
78 #[tokio::test]
79 #[ignore]
80 async fn test_fetch_photo() {
81 dotenv().ok();
82 let api_key = env::var("PEXELS_API_KEY").expect("PEXELS_API_KEY not set");
83 let client = Pexels::new(api_key);
84
85 let get_photo = FetchPhoto::builder().id(10967).build();
86 let result = get_photo.fetch(&client).await;
87 println!("get_photo result: {result:?}");
88 assert!(result.is_ok());
89 }
90}