use crate::client_credentials::GresiqCredentials;
use crate::error::GresiqError;
use serde::Serialize;
use smbcloud_network::environment::Environment;
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct GresiqClient {
base_url: String,
api_key: String,
api_secret: String,
extra_headers: HashMap<String, String>,
http: reqwest::Client,
}
impl GresiqClient {
pub fn from_credentials(environment: Environment, credentials: GresiqCredentials<'_>) -> Self {
let base_url = crate::client_credentials::base_url(&environment);
GresiqClient {
base_url,
api_key: credentials.api_key.to_string(),
api_secret: credentials.api_secret.to_string(),
extra_headers: HashMap::new(),
http: reqwest::Client::new(),
}
}
pub fn with_extra_headers(mut self, headers: HashMap<String, String>) -> Self {
self.extra_headers = headers;
self
}
pub async fn insert<T: Serialize>(&self, table: &str, record: &T) -> Result<(), GresiqError> {
let url = format!("{}/gresiq/v1/{}", self.base_url, table);
let body = serde_json::json!({ "record": record });
let mut builder = self
.http
.post(&url)
.header("X-Gresiq-Api-Key", &self.api_key)
.header("X-Gresiq-Api-Secret", &self.api_secret)
.json(&body);
for (key, value) in &self.extra_headers {
builder = builder.header(key.as_str(), value.as_str());
}
let response = builder.send().await?;
if response.status().is_success() {
log::debug!("gresiq: {} inserted ok", table);
return Ok(());
}
let status = response.status().as_u16();
let message = response
.text()
.await
.unwrap_or_else(|_| "unreadable response body".to_string());
Err(GresiqError::Api { status, message })
}
}