simple_notion/
client.rs

1#[derive(Default, Debug, Clone)]
2pub struct NotionClient {
3    pub url: crate::notion::NotionURL,
4    pub token: String,
5}
6
7impl NotionClient {
8    pub fn set_url(&mut self, url: &str) {
9        self.url = crate::notion::NotionURL::new(url);
10    }
11    
12    pub fn set_token(&mut self, token: &str) {
13        self.token = token.to_owned();
14    }
15    
16    pub async fn get_table(&self) -> Result<String, String> {
17        let client = reqwest::Client::new();
18        let database_id = self.url.data_base_id.clone();
19        
20        let url = format!("{}{}{}", crate::non_magic::notion::NOTION_API_DATABASE_START_URL, database_id, crate::non_magic::notion::NOTION_API_DATABASE_END_URL);
21        
22        match client.post(url)
23        .header(reqwest::header::AUTHORIZATION, &format!("Bearer {}", self.token))
24        .header(crate::non_magic::notion::NOTION_API_VERSION_HEADER, crate::non_magic::notion::NOTION_API_VERSION_VALUE)
25        .send()
26        .await {
27            Ok(response) => {
28                Ok(match response.text().await {
29                    Ok(text) => text,
30                    Err(error) => {
31                        return Err(error.to_string());
32                    }
33                })
34            }
35            Err(error) => {
36                Err(error.to_string())
37            }
38        }
39    }
40    
41    pub fn get_table_sync(&self) -> Result<String, String> {
42        tokio::runtime::Runtime::new().unwrap().block_on(self.get_table())
43    }
44
45    pub async fn set_data_base_element(&self, line: &str, column: &str, element: crate::notion_data_base::DataType) {
46        let value = element.to_json(column);
47        let mut cmd = format!("\"filter\": {{
48            \"property\": \"{}\",
49            \"title\": {{
50                \"equals\": \"New Record\"
51            }}
52        }},", column);
53
54        cmd.push_str(&format!("\"properties\": {{ {} }}", value));
55        cmd = format!("{{{}}}", cmd); 
56
57        println!("Out: {}", cmd);
58
59        let client = reqwest::Client::new();
60        let database_id = self.url.data_base_id.clone();
61
62        let url = format!("{}{}{}", crate::non_magic::notion::NOTION_API_DATABASE_START_URL, database_id, crate::non_magic::notion::NOTION_API_DATABASE_END_URL);
63
64        match client.post(url)
65        .header(reqwest::header::AUTHORIZATION, &format!("Bearer {}", self.token))
66        .header(crate::non_magic::notion::NOTION_API_VERSION_HEADER, crate::non_magic::notion::NOTION_API_VERSION_VALUE)
67        .header("Content-Type", "Content-Type: application/json")
68        .body(cmd).send().await {
69            Ok(response) => {
70                println!("{}", response.text().await.unwrap());
71            }
72            Err(error) => {
73                println!("{}", error.to_string());
74            }
75        }
76    }
77}