use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::config::ResolvedContext;
use crate::error::CliError;
pub fn build_client() -> reqwest::Client {
reqwest::Client::new()
}
pub async fn get_json<T: DeserializeOwned>(ctx: &ResolvedContext, path: &str) -> Result<T, CliError> {
let url = format!("{}{path}", ctx.api_url);
let client = build_client();
let mut req = client.get(&url);
if let Some(ref key) = ctx.api_key {
req = req.bearer_auth(key);
}
let resp = req.send().await?.error_for_status()?;
let body = resp.json::<T>().await?;
Ok(body)
}
pub async fn post_json<B: Serialize, T: DeserializeOwned>(
ctx: &ResolvedContext,
path: &str,
body: &B,
) -> Result<T, CliError> {
let url = format!("{}{path}", ctx.api_url);
let client = build_client();
let mut req = client.post(&url).json(body);
if let Some(ref key) = ctx.api_key {
req = req.bearer_auth(key);
}
let resp = req.send().await?.error_for_status()?;
let result = resp.json::<T>().await?;
Ok(result)
}
pub async fn post_empty<T: DeserializeOwned>(ctx: &ResolvedContext, path: &str) -> Result<T, CliError> {
let url = format!("{}{path}", ctx.api_url);
let client = build_client();
let mut req = client.post(&url);
if let Some(ref key) = ctx.api_key {
req = req.bearer_auth(key);
}
let resp = req.send().await?.error_for_status()?;
let result = resp.json::<T>().await?;
Ok(result)
}
pub async fn post_opt_json<B: Serialize, T: DeserializeOwned>(
ctx: &ResolvedContext,
path: &str,
body: Option<&B>,
) -> Result<T, CliError> {
let url = format!("{}{path}", ctx.api_url);
let client = build_client();
let mut req = match body {
Some(b) => client.post(&url).json(b),
None => client.post(&url),
};
if let Some(ref key) = ctx.api_key {
req = req.bearer_auth(key);
}
let resp = req.send().await?.error_for_status()?;
let result = resp.json::<T>().await?;
Ok(result)
}
pub async fn delete(ctx: &ResolvedContext, path: &str) -> Result<(), CliError> {
let url = format!("{}{path}", ctx.api_url);
let client = build_client();
let mut req = client.delete(&url);
if let Some(ref key) = ctx.api_key {
req = req.bearer_auth(key);
}
req.send().await?.error_for_status()?;
Ok(())
}