1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
#![deny(warnings)] use reqwest::Client; pub mod rustana_types; use rustana_types::RootInterface; use rustana_types::Dashboard; use rustana_types::Panels; use rustana_types::MutateDashboardResponse; use std::error::Error; pub struct GrafanaClient { url: String, token: String, } fn get_dashboard_by_id(base_url: &str, token: &str, _id: &str) -> Result<RootInterface, Box<Error>> { let url = format!("{}{}{}", base_url, "/api/dashboards/uid/", _id); let client = Client::new(); let res: RootInterface = client.get(&url) .header("Authorization", format!("{} {}", "Bearer", token)) .send()? .json()?; Ok(res) } fn create_or_update_dashboard(base_url: &str, token: &str, dashboard: RootInterface) -> Result<MutateDashboardResponse, Box<Error>> { let url = format!("{}{}", base_url, "/api/dashboards/db/"); let client = Client::new(); let res: MutateDashboardResponse = client.post(&url) .header("Authorization", format!("{} {}", "Bearer", token)) .json(&dashboard) .send()? .json()?; Ok(res) } impl GrafanaClient { pub fn new(url: &str, token: &str) -> GrafanaClient { GrafanaClient { url: url.to_string(), token: token.to_string(), } } pub fn get_dashboard_by_id(&mut self, _id: &str) -> Result<RootInterface, Box<Error>> { match get_dashboard_by_id(&self.url, &self.token, _id) { Ok(res) => Ok(res), Err(e) => Err(e) } } pub fn update_dashboard_by_id(&mut self, _id: &str, panels: Vec<Panels>) -> Result<MutateDashboardResponse, Box<Error>> { let dashboard = get_dashboard_by_id(&self.url, &self.token, _id); match dashboard { Ok(res) => { let new_dashboard: RootInterface = RootInterface { meta: res.meta, dashboard: Dashboard { panels: panels, ..res.dashboard } }; let updated_dashboard = create_or_update_dashboard(&self.url, &self.token, new_dashboard); match updated_dashboard { Ok(res) => Ok(res), Err(e) => Err(e), } }, Err(e) => Err(e), } } }