Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
use std::env;
use serde_derive::Deserialize;
use anyhow::Result;
const EMAIL: &'static str = "ikamat.kmr@gmail.com";
const SUMMARY_URL:&'static str = "https://api.track.toggl.com/reports/api/v2/summary";
#[tokio::main]
async fn main() -> Result<()> {
let toggl_token = env::var("TOGGL_TOKEN")?;
let workspace_id = env::var("WORKSPACE_ID")?;
let proj_data = get_report(&toggl_token, &workspace_id).await?;
let track: Track = serde_json::from_str(&proj_data)?;
println!("{:?}", track);
Ok(())
}
async fn get_report(token: &str, workspace_id: &str) -> Result<String> {
let client = reqwest::Client::new();
let query = [
("user_agent", EMAIL),
("workspace_id", workspace_id),
];
let req = client
.get(SUMMARY_URL)
.query(&query)
.basic_auth(token, Some("api_token"));
println!("{:?}", req);
let res = req
.send().await?
.text().await?;
Ok(res)
}
#[derive(Deserialize, Debug, Eq, PartialEq)]
struct EntryTitle {
#[serde(rename = "time_entry")]
title: String,
}
#[derive(Deserialize, Debug, Eq, PartialEq)]
struct Entry {
time: i64,
#[serde(rename = "title")]
entry_name: EntryTitle,
}
#[derive(Deserialize, Debug, Eq, PartialEq)]
struct ProjectTitle {
#[serde(rename = "project")]
title: String,
}
#[derive(Deserialize, Debug, Eq, PartialEq)]
struct Project {
time: i64,
#[serde(rename = "title")]
proj_name: ProjectTitle,
#[serde(rename = "items")]
entries: Vec<Entry>,
}
#[derive(Deserialize, Debug, Eq, PartialEq)]
struct Track {
#[serde(rename = "total_grand")]
time: i64,
#[serde(rename = "data")]
projs: Vec<Project>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_json() {
let data = r#"
{
"total_grand":7420000,
"total_billable":null,
"total_currencies":
[
{
"currency":null,
"amount":null
}
],
"data":
[
{
"id":162834023,
"title":
{
"project":"Personal",
"client":null,
"color":"0",
"hex_color":"hoge"
},
"time":141000,
"total_currencies":
[
{
"currency":null,
"amount":null
}
],
"items":
[
{
"title":
{
"time_entry":"todoist"
},
"time":141000,
"cur":null,
"sum":null,
"rate":null
}
]
}
]
}"#;
let track: Track = serde_json::from_str(data).unwrap();
let ans = Track {
time: 7420000,
projs: vec![
Project {
time: 141000,
proj_name: ProjectTitle {
title: "Personal".to_string(),
},
entries: vec![
Entry {
time: 141000,
entry_name: EntryTitle {
title: "todoist".to_string(),
},
},
],
},
],
};
assert_eq!(track, ans);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment