rustana/
lib.rs

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