use reqwest::{Response, header};
pub struct Client {
pub base_url: String,
client: reqwest::Client
}
impl Client {
pub fn new(base_url: String) -> Client {
Client {
base_url,
client: reqwest::Client::new()
}
}
pub fn new_auth(base_url: String, auth_token: String) -> Client {
let mut headers = header::HeaderMap::new();
match header::HeaderValue::from_str(auth_token.as_str()) {
Ok(val) => {
headers.insert(header::AUTHORIZATION, val);
}
Err(e) => {
println!("{:?}", e)
}
}
Client {
base_url,
client: reqwest::Client::builder()
.default_headers(headers)
.build()
.unwrap()
}
}
pub async fn post<T: serde::ser::Serialize + std::fmt::Debug>(&self, endpoint: &str, data: T) -> Option<Response> {
let res = self.client.post(&self.format_url(endpoint))
.json(&data)
.send()
.await.ok()?;
Some(res)
}
pub async fn delete(&self, endpoint: &str) -> Option<Response> {
let res = self.client.delete(&self.format_url(endpoint))
.send()
.await.ok()?;
Some(res)
}
pub async fn patch<T: serde::ser::Serialize + std::fmt::Debug>(&self, endpoint: &str, data: T) -> Option<Response> {
let res = self.client.patch(&self.format_url(endpoint))
.json(&data)
.send()
.await.ok()?;
Some(res)
}
pub async fn put<T: serde::ser::Serialize + std::fmt::Debug>(&self, endpoint: &str, data: T) -> Option<Response> {
let res = self.client.put(&self.format_url(endpoint))
.json(&data)
.send()
.await.ok()?;
Some(res)
}
pub async fn get(&self, endpoint: &str, single: bool) -> Option<Response> {
let res;
if single {
res = self.client.get(&self.format_url(endpoint))
.header("Accept", "application/vnd.pgrst.object+json")
.send()
.await.ok()?;
} else {
res = self.client.get(&self.format_url(endpoint))
.send()
.await.ok()?;
}
Some(res)
}
pub async fn get_abs(&self, url: &str, single: bool) -> Option<Response> {
let res;
if single {
res = self.client.get(url)
.header("Accept", "application/vnd.pgrst.object+json")
.send()
.await.ok()?;
} else {
res = self.client.get(url)
.send()
.await.ok()?;
}
Some(res)
}
pub fn format_url(&self, endpoint: &str) -> String {
format!("{}{}", self.base_url, endpoint)
}
pub async fn request(&self, endpoint: &str, method: RequestMethod, data: Option<&str>) -> Option<Response> {
let d = match data {
Some(d) => d,
None => ""
};
match method {
RequestMethod::GET => {
self.get(endpoint, false).await
}
RequestMethod::POST => {
self.post(endpoint, d).await
}
RequestMethod::PUT => {
self.put(endpoint, d).await
}
RequestMethod::PATCH => {
self.patch(endpoint, d).await
}
RequestMethod::DELETE => {
self.delete(endpoint).await
}
}
}
}
pub enum RequestMethod {
GET,
POST,
PUT,
PATCH,
DELETE
}