pub mod blocking;
pub mod flux;
use std::fmt::Display;
use csv::StringRecord;
pub use flux::{Precision, ReadQuery, WriteQuery};
use futures::TryFutureExt;
#[derive(Debug)]
pub struct InfluxError {
pub msg: Option<String>,
}
pub struct Client<'a> {
url: &'a str,
token: String,
reqwest_client: reqwest::Client,
}
impl<'a> Client<'a> {
pub fn new(url: &'a str, token: &'a str) -> Self {
Self {
url,
token: token.to_owned(),
reqwest_client: reqwest::Client::new(),
}
}
pub fn from_env(url: &'a str) -> Result<Self, InfluxError> {
Ok(Self {
url,
token: std::env::var("INFLUXDB_TOKEN").map_err(|e| InfluxError {
msg: Some(e.to_string()),
})?,
reqwest_client: reqwest::Client::new(),
})
}
pub async fn insert<T: Display>(
&self,
bucket: &'a str,
org: &'a str,
precision: Precision,
query: WriteQuery<'a, T>,
) -> Result<(), InfluxError> {
self.reqwest_client
.post(&format!(
"{}/api/v2/write?org={}&bucket={}&precision={}",
self.url, org, bucket, precision
))
.header("Authorization", &format!("Token {}", self.token))
.body(query.to_string())
.send()
.map_err(|e| InfluxError {
msg: Some(e.to_string()),
})
.await?;
Ok(())
}
pub async fn get(&self, org: &'a str, query: ReadQuery<'a>) -> Result<String, InfluxError> {
self.get_raw(org, &query.to_string()).await
}
pub async fn get_csv(
&self,
org: &'a str,
query: ReadQuery<'a>,
) -> Result<Vec<StringRecord>, InfluxError> {
let res = self.get(org, query).await?;
let reader = csv::ReaderBuilder::new().from_reader(res.as_bytes());
Ok(reader.into_records().map(|r| r.unwrap()).collect())
}
pub async fn get_raw(&self, org: &'a str, query: &'a str) -> Result<String, InfluxError> {
self.reqwest_client
.post(&format!("{}/api/v2/query?org={}", self.url, org))
.header("Accept", "application/csv")
.header("Content-Type", "application/vnd.flux")
.header("Authorization", &format!("Token {}", self.token))
.body(query.to_owned())
.send()
.await
.map_err(|e| InfluxError {
msg: Some(e.to_string()),
})?
.text()
.await
.map_err(|e| InfluxError {
msg: Some(e.to_string()),
})
}
}