use crate::api::BuildRequest;
#[cfg(not(feature = "blocking"))]
use async_trait::async_trait;
use serde::de::DeserializeOwned;
#[cfg(not(feature = "blocking"))]
type RequestClient = reqwest::Client;
#[cfg(feature = "blocking")]
type RequestClient = reqwest::blocking::Client;
pub struct Client {
reqwest_client: RequestClient,
gpt_token: String,
}
impl Client {
pub fn new(token: String) -> Self {
Client {
reqwest_client: RequestClient::new(),
gpt_token: token,
}
}
#[must_use]
pub fn gpt_token(&self) -> &str {
self.gpt_token.as_ref()
}
#[must_use]
pub fn reqwest_client(&self) -> &RequestClient {
&self.reqwest_client
}
}
#[cfg_attr(not(feature = "blocking"), async_trait)]
pub trait Request
where
Self: BuildRequest,
Self::Response: DeserializeOwned,
{
type Response;
#[cfg(feature = "blocking")]
fn request(
&self,
client: &Client,
) -> reqwest::Result<<Self as crate::client::Request>::Response> {
let response = self.build_request(client).send()?;
let json = response.json()?;
Ok(json)
}
#[cfg(feature = "blocking")]
fn request_raw(&self, client: &Client) -> reqwest::Result<String> {
let response = self.build_request(client).send()?;
let text = response.text()?;
Ok(text)
}
#[cfg(not(feature = "blocking"))]
async fn request(
&self,
client: &Client,
) -> reqwest::Result<<Self as crate::client::Request>::Response> {
let response = self.build_request(client).send().await?;
let json = response.json().await?;
Ok(json)
}
#[cfg(not(feature = "blocking"))]
async fn request_raw(&self, client: &Client) -> reqwest::Result<String> {
let response = self.build_request(client).send().await?;
let text = response.text().await?;
Ok(text)
}
}