Skip to content

Commit

Permalink
refactor(api, async)!: add fn send_async to trait Client, apply to
Browse files Browse the repository at this point in the history
async

- add new `trait Client` behavior: `send_async`.
- apply new APIs to `AsyncClient`, create new `handler` to build request
  and send with `reqwest` HTTP client.
  • Loading branch information
oleonardolima committed Sep 17, 2024
1 parent 30ad18f commit b41d756
Show file tree
Hide file tree
Showing 5 changed files with 224 additions and 290 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ log = "^0.4"
minreq = { version = "2.11.0", features = ["json-using-serde"], optional = true }
reqwest = { version = "0.11", optional = true, default-features = false, features = ["json"] }
serde_json = { version = "1.0.127" }
async-trait = { version = "0.1.82" }

[dev-dependencies]
serde_json = "1.0"
Expand Down
38 changes: 26 additions & 12 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
//! See: <https://github.com/Blockstream/esplora/blob/master/API.md>

use core::str;
use std::{collections::HashMap, str::FromStr};
use std::{future::Future, str::FromStr};

use async_trait::async_trait;
use bitcoin::consensus::Decodable;
pub use bitcoin::consensus::{deserialize, serialize};
use bitcoin::hashes::sha256::Hash;
Expand Down Expand Up @@ -46,25 +47,25 @@ impl Request {
pub struct Response {
pub status_code: i32,
pub body: Vec<u8>,
pub reason: String,
pub headers: HashMap<String, String>,
pub url: Url,
// pub reason: String,
// pub headers: HashMap<String, String>,
// pub url: Url,
}

impl Response {
pub fn new(
status_code: i32,
body: Vec<u8>,
reason_phrase: String,
headers: HashMap<String, String>,
url: Url,
// reason_phrase: String,
// headers: HashMap<String, String>,
// url: Url,
) -> Self {
Self {
status_code,
body,
reason: reason_phrase,
headers,
url,
// reason: reason_phrase,
// headers,
// url,
}
}

Expand Down Expand Up @@ -375,6 +376,7 @@ pub enum Error<E> {
Client(E),
}

#[async_trait]
pub trait Client {
fn request(&self, base_url: &str) -> Request;

Expand All @@ -383,9 +385,21 @@ pub trait Client {
F: FnMut(Request) -> Result<Response, E>,
{
let request = self.request(base_url);
let response = handler(request).map_err(Error::Client)?;
handler(request).map_err(Error::Client)
}

Ok(response)
async fn send_async<'a, F, Fut, E>(
&'a self,
base_url: &'a str,
handler: &'a mut F,
) -> Result<Response, Error<E>>
where
F: FnMut(Request) -> Fut + Send,
Fut: Future<Output = Result<Response, E>> + Send + Sync,
Self: Sync,
{
let request = self.request(base_url);
handler(request).await.map_err(Error::Client)
}

fn deserialize_decodable<T: Decodable>(&self, response: &Response) -> Result<T, crate::Error>;
Expand Down
Loading

0 comments on commit b41d756

Please sign in to comment.