10 个版本 (5 个破坏性更新)
0.6.2 | 2024年8月12日 |
---|---|
0.6.1 | 2024年7月4日 |
0.5.0 | 2023年9月7日 |
0.4.2 | 2022年6月13日 |
0.3.0 | 2022年2月19日 |
#126 in WebAssembly
每月下载量 7,330
用于 40 个 crates (直接使用 11 个)
文件大小 30KB
代码行数 443 (不包括注释)
rexie
Rexie 是一个易于使用的、基于 futures 的 IndexedDB 包装器,编译为 WebAssembly。
使用方法
要使用 Rexie,您需要在 Cargo.toml
中添加以下内容
[dependencies]
rexie = "0.6"
示例
要创建一个新的数据库,可以使用 Rexie::builder
方法
use rexie::*;
async fn build_database() -> Result<Rexie> {
// Create a new database
let rexie = Rexie::builder("test")
// Set the version of the database to 1.0
.version(1)
// Add an object store named `employees`
.add_object_store(
ObjectStore::new("employees")
// Set the key path to `id`
.key_path("id")
// Enable auto increment
.auto_increment(true)
// Add an index named `email` with the key path `email` with unique enabled
.add_index(Index::new("email", "email").unique(true)),
)
// Build the database
.build()
.await?;
// Check basic details of the database
assert_eq!(rexie.name(), "test");
assert_eq!(rexie.version(), Ok(1));
assert_eq!(rexie.store_names(), vec!["employees"]);
Ok(rexie)
}
要添加员工,可以在创建 Transaction
后使用 Store::add
方法
use rexie::*;
async fn add_employee(rexie: &Rexie, name: &str, email: &str) -> Result<u32> {
// Create a new read-write transaction
let transaction = rexie.transaction(&["employees"], TransactionMode::ReadWrite)?;
// Get the `employees` store
let employees = transaction.store("employees")?;
// Create an employee
let employee = serde_json::json!({
"name": name,
"email": email,
});
// Convert it to `JsValue`
let employee = serde_wasm_bindgen::to_value(&employee).unwrap();
// Add the employee to the store
let employee_id = employees.add(&employee, None).await?;
// Waits for the transaction to complete
transaction.done().await?;
// Return the employee id
Ok(num_traits::cast(employee_id.as_f64().unwrap()).unwrap())
}
要获取员工,可以在创建 Transaction
后使用 Store::get
方法
use rexie::*;
async fn get_employee(rexie: &Rexie, id: u32) -> Result<Option<serde_json::Value>> {
// Create a new read-only transaction
let transaction = rexie.transaction(&["employees"], TransactionMode::ReadOnly)?;
// Get the `employees` store
let employees = transaction.store("employees")?;
// Get the employee
let employee = employees.get(id.into()).await?.unwrap();
// Convert it to `serde_json::Value` from `JsValue`
let employee: Option<serde_json::Value> = serde_wasm_bindgen::from_value(employee).unwrap();
// Return the employee
Ok(employee)
}
许可证
许可证为以下之一
- Apache License,版本 2.0 (LICENSE-APACHE)
- MIT 许可证 (LICENSE-MIT)
任选其一。
贡献
除非您明确表示,否则您提交的任何贡献,根据 Apache-2.0 许可证定义的工作,都应双重许可,如上所述,不附加任何额外条款或条件。
依赖项
约 7.5–10MB
约 182K 行代码