idb
A futures based crate for interacting with IndexedDB on browsers using webassembly.
Usage
To use idb
, you need to run following command from your project root:
cargo add idb
If you don't want to use async
/await
syntax, you can disable the futures
feature using:
cargo add idb --no-default-features
After disabling the futures
feature, you can use on_success
and on_error
methods on requests to attach
callbacks.
Example
To create a new database, you can use [Factory::open
]:
use idb::{Database, DatabaseEvent, Error, Factory, IndexParams, KeyPath, ObjectStoreParams};
async fn create_database() -> Result<Database, Error> {
let factory = Factory::new()?;
let mut open_request = factory.open("test", Some(1)).unwrap();
open_request.on_upgrade_needed(|event| {
let database = event.database().unwrap();
let mut store_params = ObjectStoreParams::new();
store_params.auto_increment(true);
store_params.key_path(Some(KeyPath::new_single("id")));
let store = database
.create_object_store("employees", store_params)
.unwrap();
let mut index_params = IndexParams::new();
index_params.unique(true);
store
.create_index("email", KeyPath::new_single("email"), Some(index_params))
.unwrap();
});
open_request.await
}
To add data to an object store, you can use [ObjectStore::add
]:
use idb::{Database, Error, TransactionMode};
use serde::Serialize;
use serde_wasm_bindgen::Serializer;
use wasm_bindgen::JsValue;
async fn add_data(database: &Database) -> Result<JsValue, Error> {
let transaction = database.transaction(&["employees"], TransactionMode::ReadWrite)?;
let store = transaction.object_store("employees").unwrap();
let employee = serde_json::json!({
"name": "John Doe",
"email": "john@example.com",
});
let id = store
.add(
&employee.serialize(&Serializer::json_compatible()).unwrap(),
None,
)
.unwrap()
.await?;
transaction.commit()?.await?;
Ok(id)
}
To get data from an object store, you can use [ObjectStore::get
]:
use idb::{Database, Error, TransactionMode};
use serde_json::Value;
use wasm_bindgen::JsValue;
async fn get_data(database: &Database, id: JsValue) -> Result<Option<Value>, Error> {
let transaction = database
.transaction(&["employees"], TransactionMode::ReadOnly)
.unwrap();
let store = transaction.object_store("employees").unwrap();
let stored_employee: Option<JsValue> = store.get(id)?.await?;
let stored_employee: Option<Value> = stored_employee
.map(|stored_employee| serde_wasm_bindgen::from_value(stored_employee).unwrap());
transaction.await?;
Ok(stored_employee)
}
For more examples on using other functionality, see the
tests directory.
License
Licensed under either of
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as
defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.