1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#[forbid(missing_docs)]
mod builder;
pub use builder::*;
use js_sys::{global, Function, Object, Promise, Reflect};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::JsFuture;
#[derive(Clone)]
pub struct KvStore {
pub(crate) this: Object,
pub(crate) get_function: Function,
pub(crate) get_with_meta_function: Function,
pub(crate) put_function: Function,
pub(crate) list_function: Function,
pub(crate) delete_function: Function,
}
impl KvStore {
pub fn create(binding: &str) -> Result<Self, KvError> {
let this = get(&global(), binding.as_ref())?;
if this.is_undefined() {
Err(KvError::InvalidKvStore(binding.into()))
} else {
Ok(Self {
get_function: get(&this, "get")?.into(),
get_with_meta_function: get(&this, "getWithMetadata")?.into(),
put_function: get(&this, "put")?.into(),
list_function: get(&this, "list")?.into(),
delete_function: get(&this, "delete")?.into(),
this: this.into(),
})
}
}
pub async fn get(&self, name: &str) -> Result<Option<KvValue>, KvError> {
let name = JsValue::from(name);
let promise: Promise = self.get_function.call1(&self.this, &name)?.into();
let inner = JsFuture::from(promise)
.await
.map_err(KvError::from)?
.as_string()
.map(KvValue);
Ok(inner)
}
pub async fn get_with_metadata<M: DeserializeOwned>(
&self,
name: &str,
) -> Result<Option<(KvValue, M)>, KvError> {
let name = JsValue::from(name);
let promise: Promise = self.get_with_meta_function.call1(&self.this, &name)?.into();
let pair = JsFuture::from(promise).await?;
let metadata = get(&pair, "metadata")?;
let value = get(&pair, "value")?;
if metadata.is_null() || metadata.is_undefined() {
return Err(KvError::InvalidMetadata(
"metadata was undefined or null".into(),
));
}
let metadata = metadata.into_serde::<M>()?;
let inner = value.as_string().map(|raw| (KvValue(raw), metadata));
Ok(inner)
}
pub fn put<T: ToRawKvValue>(&self, name: &str, value: T) -> Result<PutOptionsBuilder, KvError> {
Ok(PutOptionsBuilder {
this: self.this.clone(),
put_function: self.put_function.clone(),
name: JsValue::from(name),
value: value.raw_kv_value()?,
expiration: None,
expiration_ttl: None,
metadata: None,
})
}
pub fn list(&self) -> ListOptionsBuilder {
ListOptionsBuilder {
this: self.this.clone(),
list_function: self.list_function.clone(),
limit: None,
cursor: None,
prefix: None,
}
}
pub async fn delete(&self, name: &str) -> Result<(), KvError> {
let name = JsValue::from(name);
let promise: Promise = self.delete_function.call1(&self.this, &name)?.into();
JsFuture::from(promise).await?;
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct KvValue(String);
impl KvValue {
pub fn as_string(self) -> String {
self.0
}
pub fn as_json<T: DeserializeOwned>(self) -> Result<T, KvError> {
serde_json::from_str(&self.0).map_err(KvError::from)
}
pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
self.0.as_bytes()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListResponse {
pub keys: Vec<Key>,
pub list_complete: bool,
pub cursor: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Key {
pub name: String,
pub expiration: Option<u64>,
pub metadata: Option<Value>,
}
#[derive(Debug)]
pub enum KvError {
JavaScript(JsValue),
Serialization(serde_json::Error),
InvalidKvStore(String),
InvalidMetadata(String),
}
impl Into<JsValue> for KvError {
fn into(self) -> JsValue {
match self {
Self::JavaScript(value) => value,
Self::Serialization(e) => format!("KvError::Serialization: {}", e.to_string()).into(),
Self::InvalidKvStore(binding) => format!("KvError::InvalidKvStore: {}", binding).into(),
Self::InvalidMetadata(message) => {
format!("KvError::InvalidMetadata: {}", message).into()
}
}
}
}
impl From<JsValue> for KvError {
fn from(value: JsValue) -> Self {
Self::JavaScript(value)
}
}
impl From<serde_json::Error> for KvError {
fn from(value: serde_json::Error) -> Self {
Self::Serialization(value)
}
}
pub trait ToRawKvValue {
fn raw_kv_value(&self) -> Result<JsValue, KvError>;
}
impl ToRawKvValue for str {
fn raw_kv_value(&self) -> Result<JsValue, KvError> {
Ok(JsValue::from(self))
}
}
impl<T: Serialize> ToRawKvValue for T {
fn raw_kv_value(&self) -> Result<JsValue, KvError> {
JsValue::from_serde(self).map_err(Into::into)
}
}
fn get(target: &JsValue, name: &str) -> Result<JsValue, JsValue> {
Reflect::get(target, &JsValue::from(name))
}