use anyhow::{anyhow, Context, Result};
use serde::de::DeserializeOwned;
use serde::Serialize;
use tokio::io::AsyncWriteExt;
use wavekat_platform_client::{Client as Inner, Token};
use crate::config::{self, AuthConfig};
pub struct Client {
inner: Inner,
}
impl Client {
pub fn from_config() -> Result<Self> {
let cfg = config::load()?;
Self::new(&cfg)
}
pub fn new(cfg: &AuthConfig) -> Result<Self> {
let token = cfg.token.as_deref().ok_or_else(|| {
if cfg.session_cookie.is_some() {
anyhow!("legacy session-cookie auth is no longer supported — run `wk login` to mint a wk_ token")
} else {
anyhow!("no credentials in config — run `wk login` to authenticate")
}
})?;
let inner =
Inner::new(cfg.base_url.as_str(), Token::new(token)).context("building HTTP client")?;
Ok(Self { inner })
}
pub fn base_url_for_display(&self) -> &str {
self.inner.base_url()
}
pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
Ok(self.inner.get_json(path).await?)
}
pub async fn post_empty(&self, path: &str) -> Result<()> {
Ok(self.inner.post_empty(path).await?)
}
pub async fn post_empty_returning_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
Ok(self.inner.post_empty_returning_json(path).await?)
}
pub async fn get_json_query<T: DeserializeOwned, Q: Serialize + ?Sized>(
&self,
path: &str,
query: &Q,
) -> Result<T> {
Ok(self.inner.get_json_query(path, query).await?)
}
pub async fn post_json<T: DeserializeOwned, B: Serialize + ?Sized>(
&self,
path: &str,
body: &B,
) -> Result<T> {
Ok(self.inner.post_json(path, body).await?)
}
pub async fn delete(&self, path: &str) -> Result<()> {
Ok(self.inner.delete(path).await?)
}
pub async fn put_proxy_bytes(&self, path: &str, body: Vec<u8>) -> Result<()> {
Ok(self.inner.put_proxy_bytes(path, body).await?)
}
pub async fn put_presigned_bytes(presigned_url: &str, body: Vec<u8>) -> Result<()> {
Ok(Inner::put_presigned_bytes(presigned_url, body).await?)
}
pub async fn get_stream_to<W: AsyncWriteExt + Unpin>(
&self,
path: &str,
sink: &mut W,
) -> Result<u64> {
Ok(self.inner.get_stream_to(path, sink).await?)
}
}