yocto_client/
lib.rs

1//
2// (c) 2019 Alexander Becker
3// Released under the MIT license.
4//
5
6pub mod error;
7mod util;
8
9use std::result;
10use util::*;
11use crate::error::ConnectionError;
12
13type Result<T> = result::Result<T, Box<std::error::Error>>;
14
15/// Represents a key-value store
16pub struct Store {
17    connection: String
18}
19
20impl Store {
21
22    /// Returns a new yocto store
23    ///
24    /// # Arguments
25    ///
26    /// * `connection` - A string slice that holds the endpoint of the yocto server
27    ///
28    pub fn new(connection: &str) -> Result<Store> {
29        // test connection
30        let result = handle("TEST", connection);
31
32        if let Err(e) = result {
33            return Err(Box::new(ConnectionError));
34        }
35
36        Ok(Store {
37            connection: connection.to_string()
38        })
39    }
40
41    /// Locates the given key inside the database and returns an Ok with the
42    /// corresponding value if existing or an None if not.
43    ///
44    /// # Arguments
45    ///
46    /// * `key` - A string slice that holds the key to look up
47    ///
48    pub fn get(&self, key: &str) -> Result<Option<String>> {
49        handle(&format!("{}{}{}", GET, SEP, key), &self.connection)
50    }
51
52    /// Inserts a value for a specified key. Returns the old value if existent.
53    ///
54    /// # Arguments
55    ///
56    /// * `key` - A string slice that holds the key to insert the value for
57    /// * `value` - The value to insert
58    ///
59    pub fn insert(&self, key: &str, value: &str) -> Result<Option<String>>  {
60        handle(&format!("{}{}{}{}{}", INSERT, SEP, key, SEP, value), &self.connection)
61    }
62
63    /// Removes the value corresponding to a key. Returns Err if key is not found.
64    ///
65    /// # Arguments
66    ///
67    /// * `key` - A string slice that holds the key to delete the value for
68    ///
69    pub fn remove(&self, key: &str) -> Result<Option<String>>  {
70        handle(&format!("{}{}{}", REMOVE, SEP, key), &self.connection)
71    }
72
73    /// Removes all key-value pairs from the database
74    ///
75    pub fn clear(&self) -> Result<Option<String>>  {
76        handle(&format!("{}", CLEAR), &self.connection)
77    }
78}