use crate::error::Error;
use bytes::Bytes;
use reqwest::{
Client,
header::{HeaderMap, HeaderValue},
};
use url::Url;
mod endpoint;
pub use endpoint::Endpoint;
mod list_file;
pub use list_file::ListFile;
#[derive(Debug, Clone)]
pub struct EdgeStorageClient {
pub(crate) url: Url,
pub(crate) reqwest: Client,
}
impl<'a> EdgeStorageClient {
pub async fn new<T: AsRef<str>, T1: AsRef<str>>(
api_key: T,
endpoint: Endpoint,
storage_zone: T1,
) -> Result<Self, Error> {
let mut headers = HeaderMap::new();
headers.append("AccessKey", HeaderValue::from_str(api_key.as_ref())?);
headers.append("accept", HeaderValue::from_str("application/json")?);
let reqwest = Client::builder().default_headers(headers).build()?;
let endpoint: Url = endpoint.try_into()?;
let storage_zone = String::from("/") + storage_zone.as_ref() + "/";
let url = endpoint.join(&storage_zone)?;
Ok(Self { url, reqwest })
}
pub async fn upload<T: AsRef<str>>(&self, path: T, file: Bytes) -> Result<(), Error> {
let response = self
.reqwest
.put(self.url.join(path.as_ref())?)
.header("Content-Type", "application/octet-stream")
.body(file)
.send()
.await?;
if response.status().as_u16() == 401 {
return Err(Error::Authentication(response.text().await?));
} else if response.status().as_u16() == 400 {
return Err(Error::BadRequest(response.text().await?));
}
Ok(())
}
pub async fn download<T: AsRef<str>>(&self, path: T) -> Result<Bytes, Error> {
let response = self
.reqwest
.get(self.url.join(path.as_ref())?)
.header("accept", "*/*")
.send()
.await?;
if response.status().as_u16() == 401 {
return Err(Error::Authentication(response.text().await?));
} else if response.status().as_u16() == 404 {
return Err(Error::NotFound(response.text().await?));
}
Ok(response.bytes().await?)
}
pub async fn delete<T: AsRef<str>>(&self, path: T) -> Result<(), Error> {
let response = self
.reqwest
.delete(self.url.join(path.as_ref())?)
.send()
.await?;
if response.status().as_u16() == 401 {
return Err(Error::Authentication(response.text().await?));
} else if response.status().as_u16() == 400 {
return Err(Error::BadRequest(response.text().await?));
}
Ok(())
}
pub async fn list<T: AsRef<str>>(&self, path: T) -> Result<Vec<ListFile>, Error> {
let response = self
.reqwest
.get(self.url.join(path.as_ref())?)
.send()
.await?;
if response.status().as_u16() == 401 {
return Err(Error::Authentication(response.text().await?));
} else if response.status().as_u16() == 400 {
return Err(Error::BadRequest(response.text().await?));
}
Ok(response.json().await?)
}
}