pinterest_api/api/
post_pins.rs

1use reqwest::RequestBuilder;
2use serde::{Deserialize, Serialize};
3
4use crate::{
5    api::{execute_api, ApiResponse},
6    error::Error,
7    options::{apply_options, make_url, ApiOptions},
8    parameter::media_source::MediaSource,
9    response::pin::Pin,
10};
11
12const URL_PATH: &str = "/pins";
13
14#[derive(Serialize, Deserialize, Debug, Default, Clone)]
15pub struct Body {
16    pub link: Option<String>,
17    pub title: Option<String>,
18    pub description: Option<String>,
19    pub dominant_color: Option<String>,
20    pub alt_text: Option<String>,
21    pub board_id: String,
22    pub board_section_id: Option<String>,
23    pub media_source: MediaSource,
24    pub parent_pin_id: Option<String>,
25    pub note: Option<String>,
26}
27
28#[derive(Debug, Clone, Default)]
29pub struct Api {
30    options: Option<ApiOptions>,
31    ad_account_id: Option<String>,
32    body: Body,
33}
34
35impl Api {
36    pub fn new(options: Option<ApiOptions>, body: Body) -> Self {
37        Self {
38            options,
39            body,
40            ..Default::default()
41        }
42    }
43
44    pub fn ad_account_id(mut self, ad_account_id: &str) -> Self {
45        self.ad_account_id = Some(ad_account_id.to_string());
46        self
47    }
48
49    pub fn build(self, bearer_code: &str) -> RequestBuilder {
50        let mut query_parameters = vec![];
51        if let Some(ad_account_id) = self.ad_account_id {
52            query_parameters.push(("ad_account_id", ad_account_id));
53        }
54        let client = reqwest::Client::new()
55            .post(make_url(URL_PATH, &self.options))
56            .query(&query_parameters)
57            .json(&self.body)
58            .bearer_auth(bearer_code);
59        apply_options(client, &self.options)
60    }
61
62    pub async fn execute(self, bearer_code: &str) -> Result<ApiResponse<Pin>, Error> {
63        execute_api(self.build(bearer_code)).await
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    // BEARER_CODE=xxx cargo test test_post_pins -- --nocapture --test-threads=1
72
73    #[tokio::test]
74    async fn test_post_pins() {
75        let bearer_code = std::env::var("BEARER_CODE").unwrap_or_default();
76        let body = Body {
77            board_id: "904590343843155892".to_string(),
78            media_source: MediaSource::ImageUrl {
79                url: "https://foundation.rust-lang.org/img/cargo.png".to_string(),
80                is_standard: true,
81            },
82            ..Default::default()
83        };
84        let option = ApiOptions {
85            prefix_url: Some("https://api-sandbox.pinterest.com/v5".to_string()),
86            ..Default::default()
87        };
88        let response = Api::new(Some(option), body)
89            .execute(bearer_code.as_str())
90            .await
91            .unwrap();
92        println!("{:?}", response);
93    }
94}