Skip to content

Commit

Permalink
Start refactoring routes into builder pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
Eline Jorritsma committed Nov 20, 2023
1 parent 5f2ff02 commit 944c79a
Show file tree
Hide file tree
Showing 6 changed files with 136 additions and 187 deletions.
6 changes: 0 additions & 6 deletions src/claimable_balances/single_claimable_balance_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,6 @@ impl Request for SingleClaimableBalanceRequest {
self.get_query_parameters()
)
}

fn validate(&self) -> Result<(), String> {
// TODO: Validate claimable_balance_id

Ok(())
}
}

/// Returns the claimable balance ID
Expand Down
33 changes: 9 additions & 24 deletions src/horizon_client/horizon_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,16 @@ use crate::{
AllClaimableBalancesRequest, AllClaimableBalancesResponse, SingleClaimableBalanceRequest,
SingleClaimableBalanceResponse,
},
ledgers::prelude::{
ledgers::{prelude::{
LedgersRequest, LedgersResponse, SingleLedgerRequest, SingleLedgerResponse,
},
}, single_ledger_request::Sequence},
models::{Request, Response},
};
use reqwest;
use url::Url;

use crate::accounts::prelude::*;

// region: --- States
#[derive(Default, Clone)]
pub struct Sequence(u32);
#[derive(Default, Clone)]
pub struct NoSequence;
// endregion: --- States


pub struct HorizonClient {
/// The base URL for the Horizon server
Expand Down Expand Up @@ -148,7 +141,7 @@ impl HorizonClient {
/// [GET /ledgers/{ledger_id}](https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html)
pub async fn get_single_ledger(
&self,
request: &SingleLedgerRequest,
request: &SingleLedgerRequest<Sequence>,
) -> Result<SingleLedgerResponse, String> {
self.get::<SingleLedgerResponse>(request).await
}
Expand All @@ -164,13 +157,6 @@ impl HorizonClient {
&self,
request: &impl Request,
) -> Result<TResponse, String> {
// Validate the request.
request.validate()?;

//match request by SingleAccountRequest or AccountsRequest
// Determine the url
// TODO: construct with query parameters

let url = request.build_url(&self.base_url);
let response = reqwest::get(&url).await.map_err(|e| e.to_string())?;
println!("\n\nREQWEST RESPONSE: {:?}", response);
Expand Down Expand Up @@ -717,13 +703,12 @@ mod tests {
#[tokio::test]
async fn test_get_all_ledgers() {
// Initialize horizon client

let horizon_client =
HorizonClient::new("https://horizon-testnet.stellar.org".to_string()).unwrap();

// construct request
let mut all_ledgers_request = LedgersRequest::new();
all_ledgers_request.set_limit(2);
let all_ledgers_request = LedgersRequest::new()
.set_limit(2).unwrap();

let _all_ledgers_response = horizon_client.get_all_ledgers(&all_ledgers_request).await;

Expand Down Expand Up @@ -763,8 +748,8 @@ mod tests {
HorizonClient::new("https://horizon-testnet.stellar.org".to_string()).unwrap();

// construct request
let mut single_ledger_request = SingleLedgerRequest::new();
single_ledger_request.set_sequence(2);
let mut single_ledger_request = SingleLedgerRequest::new()
.set_sequence(2).unwrap();

let _single_ledger_response = horizon_client
.get_single_ledger(&single_ledger_request)
Expand Down Expand Up @@ -912,8 +897,8 @@ mod tests {
HorizonClient::new("https://horizon-testnet.stellar.org".to_string()).unwrap();

// construct request
let mut single_ledger_request = SingleLedgerRequest::new();
single_ledger_request.set_sequence(2);
let single_ledger_request = SingleLedgerRequest::new()
.set_sequence(2).unwrap();

let _single_ledger_response = horizon_client
.get_single_ledger(&single_ledger_request)
Expand Down
138 changes: 46 additions & 92 deletions src/horizon_client/horizon_client_new.rs
Original file line number Diff line number Diff line change
@@ -1,102 +1,75 @@
use derive_getters::Getters;
use url::Url;

use crate::{models::{Response, Request}, ledgers::single_ledger_response::SingleLedgerResponse};
use crate::{models::Response, ledgers::single_ledger_response::SingleLedgerResponse};

pub trait RequestNew {
fn build_url(&self, base_url: &BaseUrl) -> String;
pub trait Req {
fn get_path(&self) -> &str;
fn build_url(&self, base_url: &str) -> String;
}

// pub trait RequestBuilder {
// fn build(self) -> Result<impl RequestNew, String>;
// }


#[derive(Clone)]
pub enum HttpMethod {
GET,
POST
}

// --------------------------------SINGLE REQUEST--------------------------------
const SINGLE_LEDGERS_PATH: &str = "/ledgers";

#[derive(Getters)]
pub struct SingleLedgerRequest {
sequence: u32,
path: String,
method: HttpMethod
}

impl RequestNew for SingleLedgerRequest {
fn build_url(&self, base_url: &BaseUrl) -> String {
format!(
"{}{}/{}",
base_url.0,
self.path(),
self.sequence()
)
}
}

// region: --- States
// region: --- SingleLedgerRequest
#[derive(Default, Clone)]
pub struct Sequence(u32);
#[derive(Default, Clone)]
pub struct NoSequence;
// endregion: --- States

#[derive(Clone)]
pub struct SingleLedgerRequestBuilder<S> {
#[derive(Default)]
pub struct SingleLedgerRequest<S> {
sequence: S,
path: String,
method: HttpMethod,
}

impl Default for SingleLedgerRequestBuilder<NoSequence> {
fn default() -> Self {
SingleLedgerRequestBuilder {
sequence: NoSequence,
path: SINGLE_LEDGERS_PATH.into(),
method: HttpMethod::GET
}
}
}

impl SingleLedgerRequestBuilder<NoSequence> {
impl SingleLedgerRequest<NoSequence> {
pub fn new() -> Self {
SingleLedgerRequestBuilder::default()
SingleLedgerRequest::default()
}
}

impl<S> SingleLedgerRequestBuilder<S> {
pub fn sequence(
impl<S> SingleLedgerRequest<S> {
pub fn set_sequence(
self,
sequence: impl Into<u32>,
) -> SingleLedgerRequestBuilder<Sequence> {

SingleLedgerRequestBuilder {
sequence: Sequence(sequence.into()),
path: SINGLE_LEDGERS_PATH.into(),
method: HttpMethod::GET
sequence: u32,
) -> Result<SingleLedgerRequest<Sequence>, String> {
if sequence < 1 {
return Err("sequence must be greater than or equal to 1".to_string());
}

Ok(
SingleLedgerRequest {
sequence: Sequence(sequence),
}
)
}
}

impl SingleLedgerRequestBuilder<Sequence> {
pub fn build(self) -> Result<SingleLedgerRequest, String> {
Ok(SingleLedgerRequest {
sequence: self.sequence.0,
path: self.path,
method: self.method
})
impl SingleLedgerRequest<Sequence> {
fn get_sequence(&self) -> String {
self.sequence.0.to_string()
}
}
// --------------------------------------------------------------------------------

impl Req for SingleLedgerRequest<Sequence> {
fn get_path(&self) -> &str {
"/ledgers"
}

fn build_url(&self, base_url: &str) -> String {
format!(
"{}{}/{}",
base_url,
self.get_path(),
self.get_sequence()
)
}
}
// endregion

// --------------------------------HORIZON CLIENT--------------------------------

// region: --- horizon-client
#[derive(Default, Clone)]
pub struct NoBaseUrl;
#[derive(Default, Clone)]
Expand Down Expand Up @@ -137,16 +110,16 @@ impl HorizonClientNew<BaseUrl> {
/// [GET /ledgers/{ledger_id}](https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html)
pub async fn get_single_ledger(
&self,
request: &SingleLedgerRequest,
request: &SingleLedgerRequest<Sequence>,
) -> Result<SingleLedgerResponse, String> {
self.get::<SingleLedgerResponse>(request).await
}

async fn get<TResponse: Response + std::fmt::Debug>(
&self,
request: &impl RequestNew
request: &impl Req
) -> Result<TResponse, String> {
let url = request.build_url(&self.base_url);
let url = request.build_url(&self.base_url.0);
let response = reqwest::get(&url).await.map_err(|e| e.to_string())?;
// println!("\n\nREQWEST RESPONSE: {:?}", response);
let result: TResponse = handle_response(response).await?;
Expand Down Expand Up @@ -181,42 +154,23 @@ fn url_validate(url_to_validate: impl Into<String>) -> Result<(), String> {

Ok(())
}
// --------------------------------------------------------------------------------------

// endregion


#[cfg(test)]
mod tests {
use base64::encode;

use crate::ledgers::single_ledger_response::SingleLedgerResponse;

use super::*;

#[test]
fn test_horizon_client() {
let horizon_client = HorizonClientNew::new()
.base_url("https://horizon-testnet.stellar.org");
}

#[test]
fn test_ledgers_request() {
let request = SingleLedgerRequestBuilder::new()
.sequence(2 as u32)
.build()
.unwrap();
}

#[tokio::test]
async fn test_get_single_ledger() {
let horizon_client = HorizonClientNew::new()
.base_url("https://horizon-testnet.stellar.org")
.unwrap();

let request = SingleLedgerRequestBuilder::new()
.sequence(2 as u32)
.build()
.unwrap();
let request = SingleLedgerRequest::new()
.set_sequence(2).unwrap();

let _single_ledger_response = horizon_client.get_single_ledger(&request).await;

Expand Down
Loading

0 comments on commit 944c79a

Please sign in to comment.