fabric_client/
client.rs

1use crate::Error;
2use serde::Serialize;
3use serde_json::Value;
4use tokio::{
5    io::{AsyncReadExt, AsyncWriteExt},
6    net::TcpStream,
7};
8
9/// Client for interacting with your fabric server
10pub struct FabricClient {
11    stream: TcpStream,
12}
13impl FabricClient {
14    /// Open a connection to your fabric server.
15    pub async fn connect(addr: &str) -> tokio::io::Result<Self> {
16        let stream = TcpStream::connect(addr).await?;
17        Ok(FabricClient { stream })
18    }
19
20    /// Perform the SET command on a provided key to
21    /// either insert, or update the value of the key.
22    ///
23    /// NOTE: That any data structure `T` for the value
24    /// must implement the `serde::Serialize` trait.
25    pub async fn set<T: Serialize>(&mut self, key: &str, value: &T) -> Result<(), Error> {
26        let serialized_data = serde_json::to_string(value).map_err(Error::BadDataStructure)?;
27
28        let command = format!("SET {} {}\n", key, serialized_data);
29        self.stream.write_all(command.as_bytes()).await?;
30        self.stream.flush().await?;
31
32        let mut buffer = vec![0; 512];
33        let n = self.stream.read(&mut buffer).await?;
34
35        let resp = String::from_utf8_lossy(&buffer[..n]);
36        if resp.contains("OK") {
37            Ok(())
38        } else {
39            Err(Error::Unknown(resp.to_string()))
40        }
41    }
42
43    /// Perform the GET command on a provided key to
44    /// grab the current value of the key.
45    pub async fn get<S: Into<String>>(&mut self, key: &str) -> Result<Value, Error> {
46        let command = format!("GET {}\n", key);
47        self.stream.write_all(command.as_bytes()).await?;
48        self.stream.flush().await?;
49
50        let mut buffer = vec![0; 512];
51        let n = self.stream.read(&mut buffer).await?;
52        let response = String::from_utf8_lossy(&buffer[..n]).to_string();
53
54        let value = serde_json::from_str(&response)?;
55        Ok(value)
56    }
57}