crux_kv/
command.rs

1//! The Command based API for `crux_kv`
2
3use std::{future::Future, marker::PhantomData};
4
5use crux_core::{command::RequestBuilder, Command, Request};
6
7use crate::{error::KeyValueError, KeyValueOperation};
8
9pub struct KeyValue<Effect, Event> {
10    // Allow the impl to declare trait bounds once. Thanks rustc
11    effect: PhantomData<Effect>,
12    event: PhantomData<Event>,
13}
14
15type StatusResult = Result<bool, KeyValueError>;
16type DataResult = Result<Option<Vec<u8>>, KeyValueError>;
17type ListResult = Result<(Vec<String>, u64), KeyValueError>;
18
19impl<Effect, Event> KeyValue<Effect, Event>
20where
21    Effect: Send + From<Request<KeyValueOperation>> + 'static,
22    Event: Send + 'static,
23{
24    pub fn get(
25        key: impl Into<String>,
26    ) -> RequestBuilder<Effect, Event, impl Future<Output = DataResult>> {
27        Command::request_from_shell(KeyValueOperation::Get { key: key.into() })
28            .map(super::KeyValueResult::unwrap_get)
29    }
30
31    pub fn set(
32        key: impl Into<String>,
33        value: Vec<u8>,
34    ) -> RequestBuilder<Effect, Event, impl Future<Output = DataResult>> {
35        Command::request_from_shell(KeyValueOperation::Set {
36            key: key.into(),
37            value,
38        })
39        .map(super::KeyValueResult::unwrap_set)
40    }
41
42    pub fn delete(
43        key: impl Into<String>,
44    ) -> RequestBuilder<Effect, Event, impl Future<Output = DataResult>> {
45        Command::request_from_shell(KeyValueOperation::Delete { key: key.into() })
46            .map(super::KeyValueResult::unwrap_delete)
47    }
48
49    pub fn exists(
50        key: impl Into<String>,
51    ) -> RequestBuilder<Effect, Event, impl Future<Output = StatusResult>> {
52        Command::request_from_shell(KeyValueOperation::Exists { key: key.into() })
53            .map(super::KeyValueResult::unwrap_exists)
54    }
55
56    pub fn list_keys(
57        prefix: impl Into<String>,
58        cursor: u64,
59    ) -> RequestBuilder<Effect, Event, impl Future<Output = ListResult>> {
60        Command::request_from_shell(KeyValueOperation::ListKeys {
61            prefix: prefix.into(),
62            cursor,
63        })
64        .map(super::KeyValueResult::unwrap_list_keys)
65    }
66}