Skip to content
This repository has been archived by the owner on Apr 6, 2024. It is now read-only.

Commit

Permalink
Add error for invalid kv bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
zebp committed Apr 22, 2021
1 parent 7fa766d commit 2439cdd
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 21 deletions.
31 changes: 19 additions & 12 deletions example/worker/worker.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});

/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest() {
const { start } = wasm_bindgen
await wasm_bindgen(wasm)
const text = await start()
const { start } = wasm_bindgen;
await wasm_bindgen(wasm);

return new Response(text, {
status: 200,
headers: {
"Content-type": "application/json"
}
})
try {
const text = await start();

return new Response(text, {
status: 200,
headers: {
"Content-type": "application/json",
},
});
} catch (error) {
return new Response(error, {
status: 500,
});
}
}
26 changes: 17 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,21 @@ pub struct KvStore {
impl KvStore {
/// Creates a new [`KvStore`] with the binding specified in your `wrangler.toml`.
pub fn create(binding: &str) -> Result<Self, KvError> {
let this: Object = get(&global(), binding.as_ref())?.into();
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,
})
let this = get(&global(), binding.as_ref())?;

// Ensures that the kv store exists.
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(),
})
}
}

/// Fetches the value from the kv store by name.
Expand Down Expand Up @@ -160,13 +166,15 @@ pub struct Key {
pub enum KvError {
JavaScript(JsValue),
Serialization(serde_json::Error),
InvalidKvStore(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(),
}
}
}
Expand Down

0 comments on commit 2439cdd

Please sign in to comment.