Skip to main content

solidb_client/client/
builder.rs

1use super::DriverError;
2use super::SoliDBClient;
3
4pub struct SoliDBClientBuilder {
5    addr: String,
6    auth: Option<AuthMethod>,
7    timeout_ms: Option<u64>,
8    pool_size: Option<usize>,
9}
10
11pub enum AuthMethod {
12    UsernamePassword {
13        database: String,
14        username: String,
15        password: String,
16    },
17    ApiKey {
18        database: String,
19        api_key: String,
20    },
21}
22
23impl SoliDBClientBuilder {
24    pub fn new(addr: &str) -> Self {
25        Self {
26            addr: addr.to_string(),
27            auth: None,
28            timeout_ms: None,
29            pool_size: None,
30        }
31    }
32
33    pub fn auth(mut self, database: &str, username: &str, password: &str) -> Self {
34        self.auth = Some(AuthMethod::UsernamePassword {
35            database: database.to_string(),
36            username: username.to_string(),
37            password: password.to_string(),
38        });
39        self
40    }
41
42    pub fn auth_with_api_key(mut self, database: &str, api_key: &str) -> Self {
43        self.auth = Some(AuthMethod::ApiKey {
44            database: database.to_string(),
45            api_key: api_key.to_string(),
46        });
47        self
48    }
49
50    pub fn timeout_ms(mut self, ms: u64) -> Self {
51        self.timeout_ms = Some(ms);
52        self
53    }
54
55    pub fn pool_size(mut self, size: usize) -> Self {
56        self.pool_size = Some(size);
57        self
58    }
59
60    pub async fn build(self) -> Result<SoliDBClient, DriverError> {
61        let pool_size = self.pool_size.unwrap_or(4);
62        let mut client = SoliDBClient::connect_with_pool(&self.addr, pool_size).await?;
63
64        if let Some(auth) = self.auth {
65            match auth {
66                AuthMethod::UsernamePassword {
67                    database,
68                    username,
69                    password,
70                } => {
71                    client.auth(&database, &username, &password).await?;
72                }
73                AuthMethod::ApiKey { database, api_key } => {
74                    client.auth_with_api_key(&database, &api_key).await?;
75                }
76            }
77        }
78
79        Ok(client)
80    }
81}