Add single http client feature

This commit is contained in:
eraden 2022-04-24 14:05:57 +02:00
parent ca5f26d356
commit a7294249d3
3 changed files with 49 additions and 13 deletions

2
Cargo.lock generated
View File

@ -2134,7 +2134,7 @@ checksum = "0c520e05135d6e763148b6426a837e239041653ba7becd2e538c076c738025fc"
[[package]]
name = "pay_u"
version = "0.1.0"
version = "0.1.2"
dependencies = [
"chrono",
"dotenv",

View File

@ -1,10 +1,14 @@
[package]
name = "pay_u"
description = "PayU Rest API wrapper"
version = "0.1.1"
version = "0.1.2"
edition = "2021"
license = "MIT"
[features]
single-client = []
default = ['single-client']
[dependencies]
reqwest = { version = "0.11.10", features = ["default", "native-tls", "json"] }

View File

@ -1,9 +1,24 @@
mod deserialize;
mod serialize;
use std::sync::Arc;
use reqwest::redirect;
use serde::{Deserialize, Serialize};
macro_rules! get_client {
($self:expr) => {{
#[cfg(feature = "single-client")]
{
$self.client.clone()
}
#[cfg(not(feature = "single-client"))]
{
Client::build_client()
}
}};
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Client is not authorized. No bearer token available")]
@ -646,6 +661,8 @@ pub struct Client {
client_secret: String,
bearer: Option<String>,
bearer_expires_at: chrono::DateTime<chrono::Utc>,
#[cfg(feature = "single-client")]
client: Arc<reqwest::Client>,
}
impl Client {
@ -658,6 +675,8 @@ impl Client {
where
ClientId: Into<String>,
ClientSecret: Into<String>,
{
#[cfg(feature = "single-client")]
{
Self {
bearer: None,
@ -666,6 +685,19 @@ impl Client {
client_id: client_id.into(),
client_secret: client_secret.into(),
bearer_expires_at: chrono::Utc::now(),
client: Arc::new(Self::build_client()),
}
}
#[cfg(not(feature = "single-client"))]
{
Self {
bearer: None,
sandbox: false,
merchant_pos_id,
client_id: client_id.into(),
client_secret: client_secret.into(),
bearer_expires_at: chrono::Utc::now(),
}
}
}
@ -735,9 +767,9 @@ impl Client {
return Err(Error::NoDescription);
}
let client = Self::build_client();
let bearer = self.bearer.as_ref().cloned().unwrap_or_default();
let path = format!("{}/orders", self.base_url());
let client = get_client!(self);
let text = client
.post(path)
.bearer_auth(bearer)
@ -802,10 +834,9 @@ impl Client {
return Err(Error::NoDescription);
}
let client = Self::build_client();
let bearer = self.bearer.as_ref().cloned().unwrap_or_default();
let path = format!("{}/orders/{}/refunds", self.base_url(), order_id);
let client = get_client!(self);
let text = client
.post(path)
.bearer_auth(bearer)
@ -833,7 +864,8 @@ impl Client {
expires_in: i64,
}
let res = Self::build_client().post(&format!(
let client = get_client!(self);
let res = client.post(&format!(
"https://secure.payu.com/pl/standard/user/oauth/authorize?grant_type=client_credentials&client_id={}&client_secret={}",
self.client_id,
self.client_secret