use std::convert::Infallible;
use anyhow::Context;
use indexed_db::Factory;
use web_sys::js_sys::JsString;
async fn example() -> anyhow::Result<()> {
let factory = Factory::get().context("opening IndexedDB")?;
let db = factory
.open::<Infallible>("database", 1, async move |evt| {
let store = evt.build_object_store("store").auto_increment().create()?;
store.add(&JsString::from("foo")).await?;
Ok(())
})
.await
.context("creating the 'database' IndexedDB")?;
db.transaction(&["store"])
.rw()
.run::<_, Infallible>(async move |t| {
let store = t.object_store("store")?;
store.add(&JsString::from("bar")).await?;
store.add(&JsString::from("baz")).await?;
Ok(())
})
.await?;
db.transaction(&["store"])
.run::<_, std::io::Error>(async move |t| {
let data = t.object_store("store")?.get_all(Some(1)).await?;
if data.len() != 1 {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Unexpected data length",
))?;
}
Ok(())
})
.await?;
db.transaction(&["store"])
.rw()
.run::<_, std::io::Error>(async move |t| {
let store = t.object_store("store")?;
store.add(&JsString::from("quux")).await?;
if store.count().await? > 3 {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Too many objects in store",
))?;
}
Ok(())
})
.await
.unwrap_err();
db.transaction(&["store"])
.run::<_, Infallible>(async move |t| {
let num_items = t.object_store("store")?.count().await?;
assert_eq!(num_items, 3);
Ok(())
})
.await?;
db.transaction(&["store"])
.run::<_, Infallible>(async move |t| {
let mut all_items = Vec::new();
let mut cursor = t.object_store("store")?.cursor().open().await?;
while let Some(value) = cursor.value() {
all_items.push(value);
cursor.advance(1).await?;
}
assert_eq!(all_items.len(), 3);
assert_eq!(all_items[0], **JsString::from("foo"));
Ok(())
})
.await?;
Ok(())
}
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn test() {
example().await.unwrap()
}
fn main() {}