todoist_tui/sync/
client.rs

1use super::{Request, Response};
2use anyhow::Result;
3
4const SYNC_URL: &str = "https://api.todoist.com/sync/v9";
5
6#[derive(Clone)]
7pub struct Client {
8    client: reqwest::Client,
9    sync_url: String,
10    api_token: String,
11}
12
13impl Client {
14    #[must_use]
15    pub fn new(api_token: &str, sync_url_override: Option<&str>) -> Self {
16        Client {
17            sync_url: sync_url_override
18                .map_or(SYNC_URL.to_string(), std::string::ToString::to_string),
19            api_token: api_token.to_string(),
20            client: reqwest::Client::new(),
21        }
22    }
23
24    /// # Errors
25    ///
26    /// Returns an error if the request fails (for network reasons) or if the returned data
27    /// cannot be parsed as expected.
28    // TODO: Better error handling, specifically to handle the various types of errors that can
29    // come back from the Sync API
30    pub async fn make_request(&self, request: &Request) -> Result<Response> {
31        let client_response = self
32            .client
33            .post(format!("{}/sync", self.sync_url))
34            .header("Authorization", format!("Bearer {}", self.api_token))
35            .json(&request)
36            .send()
37            .await?;
38        let parsed_response = client_response.json().await?;
39        Ok(parsed_response)
40    }
41}