telemetry_sh/
lib.rs

1use reqwest::blocking::{ Client };
2use serde_json::{ json, Value };
3use std::error::Error;
4
5pub struct Telemetry {
6    api_key: Option<String>,
7    base_url: String,
8}
9
10impl Telemetry {
11    pub fn new() -> Self {
12        Self {
13            api_key: None,
14            base_url: "https://api.telemetry.sh".to_string(),
15        }
16    }
17
18    pub fn init(&mut self, api_key: String) {
19        self.api_key = Some(api_key);
20    }
21
22    pub fn log(&self, table: &str, data: &Value) -> Result<Value, Box<dyn Error>> {
23        if self.api_key.is_none() {
24            return Err("API key is not initialized. Please call init() with your API key.".into());
25        }
26
27        let client = Client::new();
28        let body = json!({
29            "data": data,
30            "table": table,
31        });
32
33        let response = client
34            .post(&format!("{}/log", self.base_url))
35            .header("Content-Type", "application/json")
36            .header("Authorization", self.api_key.as_ref().unwrap())
37            .json(&body)
38            .send()?;
39
40        let json_response: Value = response.json()?;
41        Ok(json_response)
42    }
43
44    pub fn query(&self, query: &str) -> Result<Value, Box<dyn Error>> {
45        if self.api_key.is_none() {
46            return Err("API key is not initialized. Please call init() with your API key.".into());
47        }
48
49        let client = Client::new();
50        let body =
51            json!({
52            "query": query,
53            "realtime": true,
54            "json": true,
55        });
56
57        let response = client
58            .post(&format!("{}/query", self.base_url))
59            .header("Content-Type", "application/json")
60            .header("Authorization", self.api_key.as_ref().unwrap())
61            .json(&body)
62            .send()?;
63
64        let json_response: Value = response.json()?;
65        Ok(json_response)
66    }
67}