dicedb_rs/client.rs
1//! # Client Module
2//! The client module contains the main client struct and its implementation.
3//! The SDK is centered around the `Client` struct, which is used to interact with the DiceDB
4//! server.
5use crate::commandstream::CommandStream;
6use crate::errors::ClientError;
7use crate::stream::Stream;
8
9/// The main client struct used to interact with the DiceDB server.
10/// Create a new client with `Client::new(host: String, port: u16)`.
11#[derive(Debug)]
12pub struct Client {
13 pub(crate) port: u16,
14 pub(crate) host: String,
15 pub(crate) command_client: CommandStream,
16}
17
18impl Client {
19 /// Create a new client with the given host and port.
20 /// # Example
21 /// ```
22 /// use dicedb_rs::client::Client;
23 /// use dicedb_rs::errors::ClientError;
24 /// fn main() -> Result<(), ClientError> {
25 /// // Create a new client
26 /// let client = Client::new("localhost".to_string(), 7379)?;
27 /// Ok(())
28 /// }
29 /// ```
30 /// # Errors
31 /// Returns a [`ClientError`] if the connection to the server fails.
32 pub fn new(host: String, port: u16) -> Result<Self, ClientError> {
33 let mut command_client = CommandStream::new(host.clone(), port)?;
34 command_client.handshake()?;
35 Ok(Client {
36 command_client,
37 host,
38 port,
39 })
40 }
41}
42
43#[cfg(test)]
44mod tests {
45 use crate::watchstream::WatchStream;
46
47 use super::*;
48 const HOST: &str = "localhost";
49 const PORT: u16 = 7379;
50
51 #[test]
52 fn test_client() {
53 let d = Client::new(HOST.to_string(), PORT);
54 assert!(d.is_ok());
55 }
56
57 #[test]
58 fn test_client_error() {
59 let d = Client::new(HOST.to_string(), 0); // invalid port
60 assert!(d.is_err());
61 }
62
63 #[test]
64 fn test_client_error2() {
65 let wc = WatchStream::new(HOST.to_string(), 0); // invalid port
66 assert!(wc.is_err());
67 }
68}