Skip to content

Commit

Permalink
feat!: mercado pago client base
Browse files Browse the repository at this point in the history
  • Loading branch information
jackskelt committed Sep 2, 2023
1 parent 20c46ac commit 664005f
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod mercadopago;
74 changes: 74 additions & 0 deletions src/client/mercadopago.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use reqwest::Method;
use thiserror::Error;

use crate::API_BASE_URL;

pub struct MercadoPagoClient {
access_token: String,
client_http: reqwest::Client,
}

#[derive(Debug, Error)]
pub enum CredentialsError {
#[error("Credentials are requires")]
BadRequest,
#[error("Credentials are invalid")]
Unauthorized,
#[error("Not found")]
NotFound,
#[error("Internal Server Error")]
InternalServerError,

#[error("Error while sending request: {0}")]
RequestError(#[from] reqwest::Error),
}

impl MercadoPagoClient {
pub fn create_with_access_token(access_token: impl ToString) -> Self {
Self {
access_token: access_token.to_string(),
client_http: reqwest::Client::new(),
}
}

pub fn start_request(
&self,
method: reqwest::Method,
path: impl ToString,
) -> reqwest::RequestBuilder {
self.client_http
.request(method, format!("{API_BASE_URL}{}", path.to_string()))
.bearer_auth(&self.access_token)
}

pub async fn check_credentials(&self) -> Result<(), CredentialsError> {
let response = self
.start_request(Method::GET, "/v1/payment_methods")
.send()
.await?;

match response.status().as_u16() {
200 => Ok(()),
400 => Err(CredentialsError::BadRequest),
401 => Err(CredentialsError::Unauthorized),
404 => Err(CredentialsError::NotFound),
_ => Err(CredentialsError::InternalServerError),
}
}
}

#[cfg(test)]
mod tests {
use super::MercadoPagoClient;

#[tokio::test]
async fn create_client() {
dotenvy::dotenv().ok();

let client = MercadoPagoClient::create_with_access_token(
std::env::var("MERCADO_PAGO_ACCESS").unwrap(),
);

assert!(client.check_credentials().await.is_ok())
}
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub mod client;

pub static API_BASE_URL: &str = "https://api.mercadopago.com";

0 comments on commit 664005f

Please sign in to comment.