use crate::endpoint::SquareEndpoint;
use crate::error::SquareError;
use crate::response::SquareResponse;
use reqwest::{header, Client};
use serde::Serialize;
use std::default::Default;
#[derive(Copy, Clone)]
pub enum ClientMode {
Production,
Sandboxed,
}
impl Default for ClientMode {
fn default() -> Self {
Self::Sandboxed
}
}
#[derive(Clone)]
pub struct SquareClient {
access_token: String,
pub(crate) client_mode: ClientMode,
}
impl SquareClient {
pub fn new(access_token: &str) -> Self {
Self {
access_token: access_token.to_string(),
client_mode: Default::default(),
}
}
pub fn production(self) -> Self {
Self {
access_token: self.access_token,
client_mode: ClientMode::Production,
}
}
pub async fn request<T>(
&self,
endpoint: SquareEndpoint,
json: &T,
) -> Result<SquareResponse, SquareError>
where
T: Serialize + ?Sized,
{
let url = &self.endpoint(endpoint);
let authorization_header = format!("Bearer {}", &self.access_token);
let mut headers = header::HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
header::HeaderValue::from_str(&authorization_header)?,
);
let client = Client::builder().default_headers(headers).build()?;
let response = client.post(url).json(json).send().await?.text().await?;
Ok(serde_json::from_str(&response)?)
}
}