use enum_as_inner::EnumAsInner;
use reqwest::{multipart, RequestBuilder, Response};
use serde::Deserialize;
use serde_json::Value;
use std::env;
use std::error::Error;
pub type APIResponse = Result<Response, Box<dyn Error>>;
pub type IndexResults = Result<Vec<IndexResult>, Box<dyn Error>>;
pub type IndexResultsBatch = Result<Vec<Vec<IndexResult>>, Box<dyn Error>>;
pub type Strings = Result<String, Box<dyn Error>>;
pub type StringsBatch = Result<Vec<String>, Box<dyn Error>>;
pub type Texts = Result<Text, Box<dyn Error>>;
pub type TextsBatch = Result<Vec<Text>, Box<dyn Error>>;
pub struct API {
url: String,
token: String
}
impl API {
pub fn new() -> API {
API {
url: env::var("TXTAI_API_URL").unwrap_or(String::from("")),
token: env::var("TXTAI_API_TOKEN").unwrap_or(String::from(""))
}
}
pub fn with_url(url: &str) -> API {
API {
url: url.to_string(),
token: env::var("TXTAI_API_TOKEN").unwrap_or(String::from(""))
}
}
pub fn with_url_token(url: &str, token: &str) -> API {
API {
url: url.to_string(),
token: token.to_string()
}
}
pub async fn get(&self, method: &str, params: &[(&str, &str)]) -> APIResponse {
let url = format!("{url}/{method}", url=self.url, method=method);
let client = reqwest::Client::new();
let mut request = client.get(&url);
request = self.headers(request);
Ok(request.query(¶ms).send().await?)
}
pub async fn post(&self, method: &str, json: &Value) -> APIResponse {
let url = format!("{url}/{method}", url=self.url, method=method);
let client = reqwest::Client::new();
let mut request = client.post(&url);
request = self.headers(request);
Ok(request.json(&json).send().await?)
}
pub fn headers(&self, request: RequestBuilder) -> RequestBuilder {
if self.token != "" {
return request.header("Authorization", format!("Bearer {token}", token=self.token))
}
return request
}
pub async fn post_multipart(&self, method: &str, form: multipart::Form) -> APIResponse {
let url = format!("{url}/{method}", url=self.url, method=method);
let client = reqwest::Client::new();
let mut request = client.post(&url);
request = self.headers(request);
Ok(request.multipart(form).send().await?)
}
}
#[derive(Debug, Deserialize)]
pub struct IndexResult {
pub id: usize,
pub score: f32
}
#[derive(Debug, Deserialize, EnumAsInner)]
#[serde(untagged)]
pub enum Text {
String(String),
List(Vec<String>)
}