|
| 1 | +//! Mempool client builder |
| 2 | +
|
| 3 | +#[cfg(feature = "socks")] |
| 4 | +use std::net::SocketAddr; |
| 5 | +use std::time::Duration; |
| 6 | + |
| 7 | +#[cfg(feature = "socks")] |
| 8 | +use reqwest::Proxy; |
| 9 | +use reqwest::{Client, ClientBuilder}; |
| 10 | +use url::Url; |
| 11 | + |
| 12 | +use crate::client::MempoolClient; |
| 13 | +use crate::error::Error; |
| 14 | + |
| 15 | +/// Mempool client builder |
| 16 | +#[derive(Debug, Clone)] |
| 17 | +pub struct MempoolClientBuilder { |
| 18 | + /// Endpoint URL |
| 19 | + pub url: Url, |
| 20 | + /// Timeout for requests |
| 21 | + pub timeout: Duration, |
| 22 | + /// Socks5 proxy |
| 23 | + #[cfg(feature = "socks")] |
| 24 | + pub proxy: Option<SocketAddr>, |
| 25 | +} |
| 26 | + |
| 27 | +impl MempoolClientBuilder { |
| 28 | + /// Construct a new builder |
| 29 | + pub fn new(url: Url) -> Self { |
| 30 | + Self { |
| 31 | + url, |
| 32 | + timeout: Duration::from_secs(60), |
| 33 | + #[cfg(feature = "socks")] |
| 34 | + proxy: None, |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + /// Set a custom timeout |
| 39 | + #[inline] |
| 40 | + pub fn timeout(mut self, timeout: Duration) -> Self { |
| 41 | + self.timeout = timeout; |
| 42 | + self |
| 43 | + } |
| 44 | + |
| 45 | + /// Set proxy |
| 46 | + #[inline] |
| 47 | + #[cfg(feature = "socks")] |
| 48 | + pub fn proxy(mut self, proxy: SocketAddr) -> Self { |
| 49 | + self.proxy = Some(proxy); |
| 50 | + self |
| 51 | + } |
| 52 | + |
| 53 | + /// Build mempool client |
| 54 | + pub fn build(self) -> Result<MempoolClient, Error> { |
| 55 | + // Construct builder |
| 56 | + let mut builder: ClientBuilder = Client::builder(); |
| 57 | + |
| 58 | + // Set proxy |
| 59 | + #[cfg(all(feature = "socks", not(target_arch = "wasm32")))] |
| 60 | + if let Some(proxy) = self.proxy { |
| 61 | + let proxy: String = format!("socks5h://{proxy}"); |
| 62 | + builder = builder.proxy(Proxy::all(proxy)?); |
| 63 | + } |
| 64 | + |
| 65 | + // Set timeout |
| 66 | + builder = builder.timeout(self.timeout); |
| 67 | + |
| 68 | + // Build client |
| 69 | + let client: Client = builder.build()?; |
| 70 | + |
| 71 | + // Construct client |
| 72 | + Ok(MempoolClient::from_client(self.url, client)) |
| 73 | + } |
| 74 | +} |
0 commit comments