Skip to main content

clasp_client/
builder.rs

1//! Client builder pattern
2
3use crate::{Clasp, Result};
4
5/// Builder for Clasp client
6pub struct ClaspBuilder {
7    url: String,
8    name: String,
9    features: Vec<String>,
10    token: Option<String>,
11    reconnect: bool,
12    reconnect_interval_ms: u64,
13    #[cfg(feature = "p2p")]
14    p2p_config: Option<clasp_core::P2PConfig>,
15}
16
17impl ClaspBuilder {
18    /// Create a new builder
19    pub fn new(url: &str) -> Self {
20        Self {
21            url: url.to_string(),
22            name: "Clasp Client".to_string(),
23            features: vec![
24                "param".to_string(),
25                "event".to_string(),
26                "stream".to_string(),
27            ],
28            token: None,
29            reconnect: true,
30            reconnect_interval_ms: 5000,
31            #[cfg(feature = "p2p")]
32            p2p_config: None,
33        }
34    }
35
36    /// Set client name
37    pub fn name(mut self, name: &str) -> Self {
38        self.name = name.to_string();
39        self
40    }
41
42    /// Set supported features
43    pub fn features(mut self, features: Vec<String>) -> Self {
44        self.features = features;
45        self
46    }
47
48    /// Set authentication token
49    pub fn token(mut self, token: &str) -> Self {
50        self.token = Some(token.to_string());
51        self
52    }
53
54    /// Enable/disable auto-reconnect
55    pub fn reconnect(mut self, enabled: bool) -> Self {
56        self.reconnect = enabled;
57        self
58    }
59
60    /// Set reconnect interval in milliseconds
61    pub fn reconnect_interval(mut self, ms: u64) -> Self {
62        self.reconnect_interval_ms = ms;
63        self
64    }
65
66    /// Set P2P configuration (requires p2p feature)
67    #[cfg(feature = "p2p")]
68    pub fn p2p_config(mut self, config: clasp_core::P2PConfig) -> Self {
69        self.p2p_config = Some(config);
70        self
71    }
72
73    /// Build and connect
74    pub async fn connect(self) -> Result<Clasp> {
75        let mut client = Clasp::new(
76            &self.url,
77            self.name,
78            self.features,
79            self.token,
80            self.reconnect,
81            self.reconnect_interval_ms,
82        );
83
84        // Set P2P config if provided
85        #[cfg(feature = "p2p")]
86        {
87            if let Some(p2p_config) = self.p2p_config {
88                client.set_p2p_config(p2p_config);
89            }
90        }
91
92        client.do_connect().await?;
93        Ok(client)
94    }
95}