Struct keyv::Keyv

source ·
pub struct Keyv { /* private fields */ }
Expand description

Async Key-Value Store Interface

Provides an asynchronous interface to a key-value store. This implementation allows for setting, getting, removing, and clearing key-value pairs in a datastore with an optional Time-to-Live (TTL) for keys.

The Keyv struct is generic over any implementation of the Store trait, thus can be backed by various storage engines.

§Examples

§Create a new instance with in-memory store

let keyv = Keyv::default();

§Set and get a value

let keyv = Keyv::default();

keyv.set("array", vec!["hola", "test"]).await.unwrap();

match keyv.get("array").await.unwrap() {
    Some(array) => {
        let array: Vec<String> = serde_json::from_value(array).unwrap();
        assert_eq!(array, vec!["hola".to_string(), "test".to_string()])
    }
    None => assert!(false),
}

keyv.set("string", "life long").await.unwrap();
match keyv.get("string").await.unwrap() {
    Some(string) => {
        let string: String = serde_json::from_value(string).unwrap();
        assert_eq!(string, "life long");
    }
    None => assert!(false),
}

Implementations§

source§

impl Keyv

source

pub async fn try_new<S: Store + 'static>(store: S) -> Result<Self, KeyvError>

Attempts to create a new Keyv instance with a custom store.

This function will attempt to initialize the provided store. If the initialization is successful, a new Keyv instance is returned.

§Arguments
  • store - A custom store implementing the Store trait.
§Errors

Returns KeyvError if the store fails to initialize.

§Examples
§Inmemory
let store = InMemoryStore::new();
let keyv = Keyv::try_new(store).await.unwrap();
§Postgres

let store = PostgresStoreBuilder::new()
    .uri("postgresql://postgres:postgres@localhost:5432")
    .table_name("custom_table_name")
    .build()
    .await.unwrap();
  
let keyv = Keyv::try_new(store).await.unwrap();
source

pub async fn set<T: Serialize>( &self, key: &str, value: T ) -> Result<(), KeyvError>

Sets a value for a given key without a TTL.

§Arguments
  • key - The key under which the value is stored.
  • value - The value to store. Must implement Serialize.
§Errors

Returns KeyvError if the operation fails.

§Examples
let keyv = Keyv::default();
keyv.set("key", "hello world").await.unwrap();
source

pub async fn set_with_ttl<T: Serialize>( &self, key: &str, value: T, ttl: u64 ) -> Result<(), KeyvError>

Sets a value for a given key with an expiry TTL (Time-To-Live).

§Arguments
  • key - A string slice that holds the key.
  • value - The value to be stored, which must implement Serialize.
  • ttl - The time-to-live (in seconds) for the key-value pair.
§Returns

Returns an Ok result on successful insertion, or a KeyvError on failure.

§Examples
let keyv = Keyv::default();
keyv.set_with_ttl("temp_key", "temp_value", 3600).await.unwrap(); // Expires in 1 hour
source

pub async fn get(&self, key: &str) -> Result<Option<Value>, KeyvError>

Retrieves a value based on a key.

§Arguments
  • key - A string slice that holds the key to retrieve the value for.
§Returns

Returns an Ok result with Option<Value> on success, where None indicates the key does not exist, or a KeyvError on failure.

§Examples
let keyv = Keyv::default();

keyv.set("array", vec!["hola", "test"]).await.unwrap();

match keyv.get("array").await.unwrap() {
    Some(array) => {
        let array: Vec<String> = serde_json::from_value(array).unwrap();
        assert_eq!(array, vec!["hola".to_string(), "test".to_string()])
    }
    None => assert!(false),
}

keyv.set("string", "life long").await.unwrap();
match keyv.get("string").await.unwrap() {
    Some(string) => {
        let string: String = serde_json::from_value(string).unwrap();
        assert_eq!(string, "life long");
    }
    None => assert!(false),
}
source

pub async fn remove(&self, key: &str) -> Result<(), KeyvError>

Removes a specified key from the store.

§Arguments
  • key - A string slice that represents the key to be removed.
§Returns

Returns an Ok result if the key has been successfully removed, or a KeyvError on failure.

§Examples
let keyv = Keyv::default();
keyv.remove("my_key").await.unwrap(); // Removes "my_key" from the store
source

pub async fn remove_many<T: AsRef<str> + Sync>( &self, keys: &[T] ) -> Result<(), KeyvError>

Removes multiple keys from the store in one operation.

§Arguments
  • keys - A slice of strings or string-like objects that represent the keys to be removed.
§Returns

Returns an Ok result if the keys have been successfully removed, or a KeyvError on failure.

§Examples
let keyv = Keyv::default();
keyv.remove_many(&["key1", "key2"]).await.unwrap(); // Removes "key1" and "key2"
source

pub async fn clear(&self) -> Result<(), KeyvError>

Clears the entire store, removing all key-value pairs.

§Returns

Returns an Ok result if the store has been successfully cleared, or a KeyvError on failure.

§Examples
let keyv = Keyv::default();
keyv.clear().await.unwrap(); // Clears the entire store

Trait Implementations§

source§

impl Default for Keyv

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Keyv

§

impl !RefUnwindSafe for Keyv

§

impl Send for Keyv

§

impl Sync for Keyv

§

impl Unpin for Keyv

§

impl !UnwindSafe for Keyv

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.