Skip to content

Commit bb70059

Browse files
authored
Implement Storage::get_maybe. Deprecate Storage::get (#859)
1 parent e038f03 commit bb70059

File tree

6 files changed

+45
-29
lines changed

6 files changed

+45
-29
lines changed

test/src/alarm.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,7 @@ impl DurableObject for AlarmObject {
2323
.storage()
2424
.set_alarm(Duration::from_millis(100))
2525
.await?;
26-
let alarmed: bool = match self.state.storage().get("alarmed").await {
27-
Ok(alarmed) => alarmed,
28-
Err(e) if e.to_string() == "No such value in storage." => false,
29-
Err(e) => return Err(e),
30-
};
26+
let alarmed: bool = self.state.storage().get("alarmed").await?.unwrap_or(false);
3127
Response::ok(alarmed.to_string())
3228
}
3329

test/src/counter.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ impl DurableObject for Counter {
3131
async fn fetch(&self, req: Request) -> Result<Response> {
3232
if !*self.initialized.borrow() {
3333
*self.initialized.borrow_mut() = true;
34-
*self.count.borrow_mut() = self.state.storage().get("count").await.unwrap_or(0);
34+
*self.count.borrow_mut() = self.state.storage().get("count").await?.unwrap_or(0);
3535
}
3636

3737
if req.path().eq("/ws") {
@@ -71,7 +71,7 @@ impl DurableObject for Counter {
7171
.deserialize_attachment()?
7272
.expect("websockets should have an attachment");
7373
// get and increment storage by 10
74-
let mut count: usize = self.state.storage().get("count").await.unwrap_or(0);
74+
let mut count: usize = self.state.storage().get("count").await?.unwrap_or(0);
7575
count += 10;
7676
self.state.storage().put("count", count).await?;
7777
// send value to client

test/src/durable.rs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,10 @@ impl DurableObject for MyClass {
9595
let bytes = Uint8Array::new_with_length(3);
9696
bytes.copy_from(b"123");
9797
storage.put_raw("bytes", bytes).await?;
98-
let bytes = storage.get::<Vec<u8>>("bytes").await?;
98+
let bytes = storage
99+
.get::<Vec<u8>>("bytes")
100+
.await?
101+
.expect("get after put yielded nothing");
99102
storage.delete("bytes").await?;
100103
assert_eq!(
101104
bytes, b"123",
@@ -117,12 +120,18 @@ impl DurableObject for MyClass {
117120
.await?;
118121

119122
assert_eq!(
120-
storage.get::<String>("thing").await?,
123+
storage
124+
.get::<String>("thing")
125+
.await?
126+
.expect("get('thing') yielded nothing"),
121127
"Hello there",
122128
"Didn't put the right thing with put_multiple"
123129
);
124130
assert_eq!(
125-
storage.get::<i32>("other").await?,
131+
storage
132+
.get::<i32>("other")
133+
.await?
134+
.expect("get('other') yielded nothing"),
126135
56,
127136
"Didn't put the right thing with put_multiple"
128137
);
@@ -137,13 +146,16 @@ impl DurableObject for MyClass {
137146
js_sys::Reflect::set(&obj, &JsValue::from_str("foo"), &value.into())?;
138147
storage.put_multiple_raw(obj).await?;
139148
assert_eq!(
140-
storage.get::<Vec<u8>>("foo").await?,
149+
storage
150+
.get::<Vec<u8>>("foo")
151+
.await?
152+
.expect("get('foo') yielded nothing"),
141153
BAR,
142154
"Didn't the right thing with put_multiple_raw"
143155
);
144156
}
145157

146-
*self.number.borrow_mut() = storage.get("count").await.unwrap_or(0) + 1;
158+
*self.number.borrow_mut() = storage.get("count").await?.unwrap_or(0) + 1;
147159

148160
storage.delete_all().await?;
149161

test/src/put_raw.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@ impl PutRawTestObject {
1717
let bytes = Uint8Array::new_with_length(3);
1818
bytes.copy_from(b"123");
1919
storage.put_raw("bytes", bytes).await?;
20-
let bytes = storage.get::<Vec<u8>>("bytes").await?;
20+
let bytes = storage
21+
.get::<Vec<u8>>("bytes")
22+
.await?
23+
.expect("get after put yielded nothing");
2124
storage.delete("bytes").await?;
2225
assert_eq!(
2326
bytes, b"123",
@@ -36,7 +39,10 @@ impl PutRawTestObject {
3639
storage.put_multiple_raw(obj).await?;
3740

3841
assert_eq!(
39-
storage.get::<Vec<u8>>("foo").await?,
42+
storage
43+
.get::<Vec<u8>>("foo")
44+
.await?
45+
.expect("get('foo') yielded nothing"),
4046
BAR,
4147
"Didn't get the right thing with put_multiple_raw"
4248
);

worker-build/src/main.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,12 +151,12 @@ fn generate_handlers() -> Result<String> {
151151
let mut handlers = String::new();
152152
for func_name in func_names {
153153
if func_name == "fetch" && env::var("RUN_TO_COMPLETION").is_ok() {
154-
handlers += "Entrypoint.prototype.fetch = async function fetch(request) {{
154+
handlers += "Entrypoint.prototype.fetch = async function fetch(request) {
155155
let response = exports.fetch(request, this.env, this.ctx);
156156
this.ctx.waitUntil(response);
157157
return response;
158-
}}
159-
"
158+
}
159+
";
160160
} else if func_name == "fetch" || func_name == "queue" || func_name == "scheduled" {
161161
// TODO: Switch these over to https://github.com/wasm-bindgen/wasm-bindgen/pull/4757
162162
// once that lands.

worker/src/durable.rs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -344,18 +344,20 @@ impl Storage {
344344
/// Retrieves the value associated with the given key. The type of the returned value will be
345345
/// whatever was previously written for the key.
346346
///
347-
/// Returns [Err] if the key does not exist.
348-
pub async fn get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Result<T> {
349-
JsFuture::from(self.inner.get(key)?)
350-
.await
351-
.and_then(|val| {
352-
if val.is_undefined() {
353-
Err(JsValue::from("No such value in storage."))
354-
} else {
355-
serde_wasm_bindgen::from_value(val).map_err(|e| JsValue::from(e.to_string()))
356-
}
357-
})
358-
.map_err(Error::from)
347+
/// Returns `Ok(None)` if the key does not exist.
348+
pub async fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
349+
let res = match JsFuture::from(self.inner.get(key)?).await {
350+
// If we successfully retrived `undefined`, that means the key doesn't exist
351+
Ok(val) if val.is_undefined() => Ok(None),
352+
// Otherwise deserialize whatever we successfully received
353+
Ok(val) => {
354+
serde_wasm_bindgen::from_value(val).map_err(|e| JsValue::from(e.to_string()))
355+
}
356+
// Forward any error, rewrap to make the typechecker happy
357+
Err(e) => Err(e),
358+
};
359+
360+
res.map_err(Error::from)
359361
}
360362

361363
/// Retrieves the values associated with each of the provided keys.

0 commit comments

Comments
 (0)