use nextcloud_sdk_core::{ApiPath, AuthProvider, Error, HttpMethod, Transport};
use serde::Serialize;
use serde::de::DeserializeOwned;
use super::path::{require_ocs, with_query};
use super::request::build_request;
use super::response::decode_response;
use crate::query::Query;
#[derive(Clone, Debug)]
pub struct OcsClient<T, A> {
transport: T,
auth: A,
}
impl<T: Transport, A: AuthProvider> OcsClient<T, A> {
pub const fn new(transport: T, auth: A) -> Self {
Self { transport, auth }
}
pub const fn transport(&self) -> &T {
&self.transport
}
pub const fn auth(&self) -> &A {
&self.auth
}
pub async fn get<Res: DeserializeOwned>(
&self,
path: ApiPath,
query: Query,
) -> Result<Res, Error> {
let path = with_query(&require_ocs(path)?, &query);
tracing::debug!(path = %path.as_str(), "Executing OCS GET request");
let request = build_request(HttpMethod::Get, path.clone(), None::<&()>, &self.auth)?;
let response = self.transport.execute(request).await?;
decode_response(HttpMethod::Get, path, &response)
}
pub async fn post<Req: Serialize, Res: DeserializeOwned>(
&self,
path: ApiPath,
body: &Req,
) -> Result<Res, Error> {
self.post_with_query(path, Query::new(), body).await
}
pub async fn post_with_query<Req: Serialize, Res: DeserializeOwned>(
&self,
path: ApiPath,
query: Query,
body: &Req,
) -> Result<Res, Error> {
let path = with_query(&require_ocs(path)?, &query);
tracing::debug!(path = %path.as_str(), "Executing OCS POST request");
let request = build_request(HttpMethod::Post, path.clone(), Some(body), &self.auth)?;
let response = self.transport.execute(request).await?;
decode_response(HttpMethod::Post, path, &response)
}
pub async fn put<Req: Serialize, Res: DeserializeOwned>(
&self,
path: ApiPath,
body: &Req,
) -> Result<Res, Error> {
self.put_with_query(path, Query::new(), body).await
}
pub async fn put_with_query<Req: Serialize, Res: DeserializeOwned>(
&self,
path: ApiPath,
query: Query,
body: &Req,
) -> Result<Res, Error> {
let path = with_query(&require_ocs(path)?, &query);
tracing::debug!(path = %path.as_str(), "Executing OCS PUT request");
let request = build_request(HttpMethod::Put, path.clone(), Some(body), &self.auth)?;
let response = self.transport.execute(request).await?;
decode_response(HttpMethod::Put, path, &response)
}
pub async fn delete<Res: DeserializeOwned>(&self, path: ApiPath) -> Result<Res, Error> {
self.delete_with_query(path, Query::new()).await
}
pub async fn delete_with_query<Res: DeserializeOwned>(
&self,
path: ApiPath,
query: Query,
) -> Result<Res, Error> {
let path = with_query(&require_ocs(path)?, &query);
tracing::debug!(path = %path.as_str(), "Executing OCS DELETE request");
let request = build_request(HttpMethod::Delete, path.clone(), None::<&()>, &self.auth)?;
let response = self.transport.execute(request).await?;
decode_response(HttpMethod::Delete, path, &response)
}
}