From e47d4500dd02e4fc5324cfd210e157f200097c23 Mon Sep 17 00:00:00 2001 From: Devashish Dixit Date: Mon, 13 Dec 2021 18:40:23 +0800 Subject: [PATCH] initial commit --- .appveyor.yml | 11 ++ .cargo-ok | 0 .gitignore | 7 + .travis.yml | 69 ++++++++ Cargo.toml | 49 ++++++ LICENSE_APACHE | 176 +++++++++++++++++++++ LICENSE_MIT | 25 +++ README.md | 69 ++++++++ src/error.rs | 119 ++++++++++++++ src/index.rs | 63 ++++++++ src/key_range.rs | 56 +++++++ src/lib.rs | 71 +++++++++ src/object_store.rs | 116 ++++++++++++++ src/observer.rs | 112 +++++++++++++ src/rexie.rs | 56 +++++++ src/rexie_builder.rs | 169 ++++++++++++++++++++ src/transaction.rs | 106 +++++++++++++ src/transaction/index.rs | 197 +++++++++++++++++++++++ src/transaction/store.rs | 331 +++++++++++++++++++++++++++++++++++++++ src/utils.rs | 40 +++++ tests/web.rs | 13 ++ 21 files changed, 1855 insertions(+) create mode 100644 .appveyor.yml create mode 100644 .cargo-ok create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 Cargo.toml create mode 100644 LICENSE_APACHE create mode 100644 LICENSE_MIT create mode 100644 README.md create mode 100644 src/error.rs create mode 100644 src/index.rs create mode 100644 src/key_range.rs create mode 100644 src/lib.rs create mode 100644 src/object_store.rs create mode 100644 src/observer.rs create mode 100644 src/rexie.rs create mode 100644 src/rexie_builder.rs create mode 100644 src/transaction.rs create mode 100644 src/transaction/index.rs create mode 100644 src/transaction/store.rs create mode 100644 src/utils.rs create mode 100644 tests/web.rs diff --git a/.appveyor.yml b/.appveyor.yml new file mode 100644 index 0000000..50910bd --- /dev/null +++ b/.appveyor.yml @@ -0,0 +1,11 @@ +install: + - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe + - if not defined RUSTFLAGS rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --locked diff --git a/.cargo-ok b/.cargo-ok new file mode 100644 index 0000000..e69de29 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c50a344 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/target +**/*.rs.bk +Cargo.lock +bin/ +pkg/ +wasm-pack.log +www/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..7a91325 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,69 @@ +language: rust +sudo: false + +cache: cargo + +matrix: + include: + + # Builds with wasm-pack. + - rust: beta + env: RUST_BACKTRACE=1 + addons: + firefox: latest + chrome: stable + before_script: + - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) + - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) + - cargo install-update -a + - curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f + script: + - cargo generate --git . --name testing + # Having a broken Cargo.toml (in that it has curlies in fields) anywhere + # in any of our parent dirs is problematic. + - mv Cargo.toml Cargo.toml.tmpl + - cd testing + - wasm-pack build + - wasm-pack test --chrome --firefox --headless + + # Builds on nightly. + - rust: nightly + env: RUST_BACKTRACE=1 + before_script: + - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) + - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) + - cargo install-update -a + - rustup target add wasm32-unknown-unknown + script: + - cargo generate --git . --name testing + - mv Cargo.toml Cargo.toml.tmpl + - cd testing + - cargo check + - cargo check --target wasm32-unknown-unknown + - cargo check --no-default-features + - cargo check --target wasm32-unknown-unknown --no-default-features + - cargo check --no-default-features --features console_error_panic_hook + - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook + - cargo check --no-default-features --features "console_error_panic_hook wee_alloc" + - cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc" + + # Builds on beta. + - rust: beta + env: RUST_BACKTRACE=1 + before_script: + - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) + - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) + - cargo install-update -a + - rustup target add wasm32-unknown-unknown + script: + - cargo generate --git . --name testing + - mv Cargo.toml Cargo.toml.tmpl + - cd testing + - cargo check + - cargo check --target wasm32-unknown-unknown + - cargo check --no-default-features + - cargo check --target wasm32-unknown-unknown --no-default-features + - cargo check --no-default-features --features console_error_panic_hook + - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook + # Note: no enabling the `wee_alloc` feature here because it requires + # nightly for now. diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..aebad95 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,49 @@ +[package] +name = "rexie" +version = "0.1.0" +authors = ["Devashish Dixit "] +edition = "2018" + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = ["console_error_panic_hook"] +js-test = [] +js = [] + +[dependencies] +console_error_panic_hook = { version = "0.1.6", optional = true } +js-sys = "0.3.55" +thiserror = "1.0.30" +tokio = { version = "1.14.0", features = ["macros", "sync"] } +wasm-bindgen = "0.2.63" +wasm-bindgen-futures = "0.4.28" +web-sys = { version = "0.3.55", features = [ + "console", + "DomException", + "DomStringList", + "IdbDatabase", + "IdbFactory", + "IdbIndex", + "IdbIndexParameters", + "IdbKeyRange", + "IdbObjectStore", + "IdbObjectStoreParameters", + "IdbOpenDbRequest", + "IdbOpenDbOptions", + "IdbRequest", + "IdbTransaction", + "IdbTransactionMode", + "StorageType", + "Window", +] } +wee_alloc = { version = "0.4.5", optional = true } + + +[dev-dependencies] +wasm-bindgen-test = "0.3.13" + +[profile.release] +# Tell `rustc` to optimize for small code size. +opt-level = "s" diff --git a/LICENSE_APACHE b/LICENSE_APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/LICENSE_APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/LICENSE_MIT b/LICENSE_MIT new file mode 100644 index 0000000..e8388da --- /dev/null +++ b/LICENSE_MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Devashish Dixit + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1e4617a --- /dev/null +++ b/README.md @@ -0,0 +1,69 @@ +
+ +

wasm-pack-template

+ + A template for kick starting a Rust and WebAssembly project using wasm-pack. + +

+ Build Status +

+ +

+ Tutorial + | + Chat +

+ + Built with 🦀🕸 by The Rust and WebAssembly Working Group +
+ +## About + +[**📚 Read this template tutorial! 📚**][template-docs] + +This template is designed for compiling Rust libraries into WebAssembly and +publishing the resulting package to NPM. + +Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other +templates and usages of `wasm-pack`. + +[tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html +[template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html + +## 🚴 Usage + +### 🐑 Use `cargo generate` to Clone this Template + +[Learn more about `cargo generate` here.](https://github.com/ashleygwilliams/cargo-generate) + +``` +cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project +cd my-project +``` + +### 🛠️ Build with `wasm-pack build` + +``` +wasm-pack build +``` + +### 🔬 Test in Headless Browsers with `wasm-pack test` + +``` +wasm-pack test --headless --firefox +``` + +### 🎁 Publish to NPM with `wasm-pack publish` + +``` +wasm-pack publish +``` + +## 🔋 Batteries Included + +* [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating + between WebAssembly and JavaScript. +* [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook) + for logging panic messages to the developer console. +* [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized + for small code size. diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..4ca1135 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,119 @@ +use std::fmt; + +use js_sys::Error as JsError; +use thiserror::Error; +use wasm_bindgen::prelude::*; + +#[cfg(not(feature = "js"))] +pub type Result = std::result::Result; + +#[cfg(feature = "js")] +pub type Result = std::result::Result; + +#[derive(Debug, Error, Clone)] +pub struct Error { + error_type: ErrorType, + inner: Option, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.inner { + None => write!(f, "{}", self.error_type), + Some(ref inner) => write!(f, "{}: {}", self.error_type, option_display(inner)), + } + } +} + +fn option_display(option: &JsValue) -> String { + match option.as_string() { + Some(s) => s, + None => "".to_string(), + } +} + +impl Error { + pub fn error_type(&self) -> ErrorType { + self.error_type + } + + pub(crate) fn set_inner(mut self, inner: JsValue) -> Self { + self.inner = Some(inner); + self + } +} + +impl From for Error { + fn from(error_type: ErrorType) -> Self { + Self { + error_type, + inner: None, + } + } +} + +#[derive(Debug, Error, Clone, Copy)] +pub enum ErrorType { + #[error("error when receiving message from async channel")] + AsyncChannelError, + + #[error("event target is none")] + EventTargetNotFound, + + #[error("index creation failed")] + IndexCreationFailed, + + #[error("index open failed")] + IndexOpenFailed, + + #[error("indexed db error")] + IndexedDBError, + + #[error("indexed db is none")] + IndexedDBNotFound, + + #[error("indexed db not supported")] + IndexedDBNotSupported, + + #[error("failed to open indexed db")] + IndexedDBOpenFailed, + + #[error("key range error")] + KeyRangeError, + + #[error("object store creation failed")] + ObjectStoreCreationFailed, + + #[error("failed to open object store")] + ObjectStoreOpenFailed, + + #[error("failed to execute db transaction")] + TransactionExecutionFailed, + + #[error("failed to open db transaction")] + TransactionOpenFailed, + + #[error("window object not found")] + WindowNotFound, +} + +impl ErrorType { + pub(crate) fn into_error(self) -> Error { + Error::from(self) + } +} + +impl From for JsValue { + fn from(error_type: ErrorType) -> Self { + JsError::new(&error_type.to_string()).into() + } +} + +impl From for JsValue { + fn from(error: Error) -> JsValue { + match error.inner { + Some(inner) => inner, + None => error.error_type.into(), + } + } +} diff --git a/src/index.rs b/src/index.rs new file mode 100644 index 0000000..7c4c98a --- /dev/null +++ b/src/index.rs @@ -0,0 +1,63 @@ +#[cfg(feature = "js")] +use wasm_bindgen::prelude::*; +use web_sys::{IdbIndexParameters, IdbObjectStore}; + +use crate::{ErrorType, Result}; + +#[cfg_attr(feature = "js", wasm_bindgen)] +pub struct Index { + pub(crate) name: String, + pub(crate) key_path: String, + pub(crate) unique: Option, + pub(crate) multi_entry: Option, +} + +#[cfg_attr(feature = "js", wasm_bindgen)] +impl Index { + #[cfg_attr(feature = "js", wasm_bindgen(constructor))] + pub fn new(name: &str, key_path: &str) -> Self { + Self { + name: name.to_owned(), + key_path: key_path.to_owned(), + unique: None, + multi_entry: None, + } + } + + pub fn unique(mut self, unique: bool) -> Self { + self.unique = Some(unique); + self + } + + #[cfg_attr(feature = "js", wasm_bindgen(js_name = "multiEntry"))] + pub fn multi_entry(mut self, multi_entry: bool) -> Self { + self.multi_entry = Some(multi_entry); + self + } +} + +impl Index { + pub(crate) fn create(self, object_store: &IdbObjectStore) -> Result<()> { + if !object_store.index_names().contains(&self.name) { + let mut params = IdbIndexParameters::new(); + + if let Some(unique) = self.unique { + params.unique(unique); + } + + if let Some(multi_entry) = self.multi_entry { + params.multi_entry(multi_entry); + } + + object_store + .create_index_with_str_and_optional_parameters(&self.name, &self.key_path, ¶ms) + .map_err(|js_value| { + ErrorType::IndexCreationFailed + .into_error() + .set_inner(js_value) + })?; + } + + Ok(()) + } +} diff --git a/src/key_range.rs b/src/key_range.rs new file mode 100644 index 0000000..33246c5 --- /dev/null +++ b/src/key_range.rs @@ -0,0 +1,56 @@ +#[cfg(feature = "js")] +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsValue; +use web_sys::IdbKeyRange; + +use crate::{ErrorType, Result}; + +#[cfg_attr(feature = "js", wasm_bindgen)] +pub struct KeyRange { + idb_key_range: IdbKeyRange, +} + +#[cfg_attr(feature = "js", wasm_bindgen)] +impl KeyRange { + #[cfg_attr(feature = "js", wasm_bindgen(js_name = "lowerBound"))] + pub fn lower_bound(lower_bound: &JsValue, lower_open: bool) -> Result { + let idb_key_range = IdbKeyRange::lower_bound_with_open(lower_bound, lower_open) + .map_err(|js_value| ErrorType::KeyRangeError.into_error().set_inner(js_value))?; + + Ok(KeyRange { idb_key_range }) + } + + #[cfg_attr(feature = "js", wasm_bindgen(js_name = "upperBound"))] + pub fn upper_bound(upper_bound: &JsValue, upper_open: bool) -> Result { + let idb_key_range = IdbKeyRange::upper_bound_with_open(upper_bound, upper_open) + .map_err(|js_value| ErrorType::KeyRangeError.into_error().set_inner(js_value))?; + + Ok(KeyRange { idb_key_range }) + } + + pub fn bound( + lower: &JsValue, + upper: &JsValue, + lower_open: bool, + upper_open: bool, + ) -> Result { + let idb_key_range = + IdbKeyRange::bound_with_lower_open_and_upper_open(lower, upper, lower_open, upper_open) + .map_err(|js_value| ErrorType::KeyRangeError.into_error().set_inner(js_value))?; + + Ok(Self { idb_key_range }) + } + + pub fn only(value: &JsValue) -> Result { + let idb_key_range = IdbKeyRange::only(value) + .map_err(|js_value| ErrorType::KeyRangeError.into_error().set_inner(js_value))?; + + Ok(Self { idb_key_range }) + } +} + +impl AsRef for KeyRange { + fn as_ref(&self) -> &JsValue { + self.idb_key_range.as_ref() + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..192e957 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,71 @@ +//! ## Usage +//! +//! ```rust,ignore +//! let rexie = Rexie::builder("backend") +//! .version(1) +//! .add_object_store( +//! ObjectStore::new("employees") +//! .key_path("id") +//! .add_index(Index::new("email", "email").unique(true)), +//! ) +//! .build() +//! .await?; +//! +//! web_sys::console::log_1(&rexie.name().into()); +//! ``` +mod error; +mod index; +mod key_range; +mod object_store; +mod observer; +mod rexie; +mod rexie_builder; +mod transaction; +mod utils; + +// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global +// allocator. +#[cfg(feature = "wee_alloc")] +#[global_allocator] +static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; + +pub use self::{ + error::{Error, ErrorType, Result}, + index::Index, + key_range::KeyRange, + object_store::ObjectStore, + rexie::Rexie, + rexie_builder::RexieBuilder, + transaction::{Store, StoreIndex, Transaction, TransactionMode}, +}; + +// #[cfg(feature = "js-test")] +// use wasm_bindgen::prelude::*; + +// #[cfg(feature = "js-test")] +// #[wasm_bindgen] +// pub async fn test() -> std::result::Result<(), JsValue> { +// let rexie = Rexie::builder("backend") +// .version(1) +// .add_object_store(ObjectStore::new("employees")) +// .build() +// .await?; + +// let transaction = +// rexie.transaction(vec!["employees".to_string()], TransactionMode::ReadWrite)?; +// let store = transaction.store("employees")?; + +// store.add(JsValue::from(3), JsValue::from("the"))?; +// web_sys::console::log_1(&store.count().await?.into()); + +// store.add(JsValue::from(4), JsValue::from("rock"))?; +// web_sys::console::log_1(&store.count().await?.into()); + +// transaction.finish().await?; + +// web_sys::console::log_1(&rexie.name().into()); + +// rexie.close(); + +// Ok(()) +// } diff --git a/src/object_store.rs b/src/object_store.rs new file mode 100644 index 0000000..4f3ee46 --- /dev/null +++ b/src/object_store.rs @@ -0,0 +1,116 @@ +use std::collections::HashSet; + +#[cfg(feature = "js")] +use wasm_bindgen::prelude::*; +use wasm_bindgen::UnwrapThrowExt; +use web_sys::{IdbDatabase, IdbObjectStoreParameters, IdbOpenDbRequest}; + +use crate::{ErrorType, Index, Result}; + +#[cfg_attr(feature = "js", wasm_bindgen)] +pub struct ObjectStore { + pub(crate) name: String, + pub(crate) key_path: Option, + pub(crate) auto_increment: Option, + pub(crate) indexes: Vec, +} + +#[cfg_attr(feature = "js", wasm_bindgen)] +impl ObjectStore { + #[cfg_attr(feature = "js", wasm_bindgen(constructor))] + pub fn new(name: &str) -> Self { + Self { + name: name.to_owned(), + key_path: None, + auto_increment: None, + indexes: Vec::new(), + } + } + + #[cfg_attr(feature = "js", wasm_bindgen(js_name = "keyPath"))] + pub fn key_path(mut self, key_path: &str) -> Self { + self.key_path = Some(key_path.to_owned()); + self + } + + #[cfg_attr(feature = "js", wasm_bindgen(js_name = "autoIncrement"))] + pub fn auto_increment(mut self, auto_increment: bool) -> Self { + self.auto_increment = Some(auto_increment); + self + } + + #[cfg_attr(feature = "js", wasm_bindgen(js_name = "addIndex"))] + pub fn add_index(mut self, index: Index) -> Self { + self.indexes.push(index); + self + } +} + +impl ObjectStore { + pub(crate) fn create( + self, + idb_open_request: &IdbOpenDbRequest, + idb: &IdbDatabase, + ) -> Result<()> { + let mut index_names = self.index_names(); + + let object_store = if idb.object_store_names().contains(&self.name) { + let transaction = idb_open_request + .transaction() + .ok_or_else(|| ErrorType::TransactionOpenFailed.into_error())?; + + transaction.object_store(&self.name).map_err(|js_value| { + ErrorType::ObjectStoreOpenFailed + .into_error() + .set_inner(js_value) + })? + } else { + let mut params = IdbObjectStoreParameters::new(); + + if let Some(auto_increment) = self.auto_increment { + params.auto_increment(auto_increment); + } + + if let Some(key_path) = self.key_path { + params.key_path(Some(&key_path.into())); + } + + idb.create_object_store_with_optional_parameters(&self.name, ¶ms) + .map_err(|js_value| { + ErrorType::ObjectStoreCreationFailed + .into_error() + .set_inner(js_value) + })? + }; + + for index in self.indexes { + index.create(&object_store)?; + } + + let db_index_names = object_store.index_names(); + let mut indexes_to_remove = Vec::new(); + + for index in 0..db_index_names.length() { + let db_index_name = db_index_names.get(index).unwrap_throw(); + + if index_names.contains(&db_index_name) { + index_names.remove(&db_index_name); + } else { + indexes_to_remove.push(db_index_name); + } + } + + for index_name in indexes_to_remove { + object_store.delete_index(&index_name).unwrap_throw(); + } + + Ok(()) + } + + pub(crate) fn index_names(&self) -> HashSet { + self.indexes + .iter() + .map(|index| index.name.clone()) + .collect() + } +} diff --git a/src/observer.rs b/src/observer.rs new file mode 100644 index 0000000..3e07bd0 --- /dev/null +++ b/src/observer.rs @@ -0,0 +1,112 @@ +use std::fmt::Debug; + +use js_sys::Function; +use tokio::{ + select, + sync::oneshot::{Receiver, Sender}, +}; +use wasm_bindgen::{prelude::Closure, JsCast, UnwrapThrowExt}; +use web_sys::Event; + +use crate::{ErrorType, Result}; + +pub struct ResultObserver +where + T: Debug + 'static, +{ + pub(crate) success_observer: Observer>, + pub(crate) error_observer: Observer>, +} + +impl ResultObserver +where + T: Debug + 'static, +{ + pub fn new(ok: T, err: impl Fn(&Event) -> Result + 'static) -> Self { + let success_observer = Observer::new(Ok(ok)); + let error_observer = Observer::new_lazy(err); + + Self { + success_observer, + error_observer, + } + } + + pub fn get_success_callback(&self) -> &Function { + self.success_observer.get_callback() + } + + pub fn get_error_callback(&self) -> &Function { + self.error_observer.get_callback() + } + + pub async fn finish(self) -> Result { + let res = select! { + res = self.success_observer.finish() => res, + res = self.error_observer.finish() => res, + }?; + + res + } +} + +pub struct Observer +where + T: Debug + 'static, +{ + pub(crate) closure: Closure, + pub(crate) receiver: Receiver, +} + +impl Observer +where + T: Debug + 'static, +{ + pub fn new(value: T) -> Self { + let (sender, receiver) = tokio::sync::oneshot::channel(); + build_observer(value, sender, receiver) + } + + pub fn new_lazy(f: impl Fn(&Event) -> T + 'static) -> Self { + let (sender, receiver) = tokio::sync::oneshot::channel(); + build_lazy_observer(f, sender, receiver) + } + + pub fn get_callback(&self) -> &Function { + self.closure.as_ref().unchecked_ref() + } + + pub async fn finish(self) -> Result { + let result = self + .receiver + .await + .map_err(|_| ErrorType::AsyncChannelError.into_error())?; + + Ok(result) + } +} + +fn build_observer(value: T, sender: Sender, receiver: Receiver) -> Observer +where + T: Debug + 'static, +{ + build_lazy_observer(move |_| value, sender, receiver) +} + +fn build_lazy_observer( + f: impl FnOnce(&Event) -> T + 'static, + sender: Sender, + receiver: Receiver, +) -> Observer +where + T: Debug + 'static, +{ + let closure = Closure::once(|event: Event| { + sender + .send(f(&event)) + .map_err(|_| ErrorType::AsyncChannelError.into_error()) + .unwrap_throw(); + }); + + Observer { closure, receiver } +} diff --git a/src/rexie.rs b/src/rexie.rs new file mode 100644 index 0000000..424d372 --- /dev/null +++ b/src/rexie.rs @@ -0,0 +1,56 @@ +use js_sys::Array; +#[cfg(feature = "js")] +use wasm_bindgen::prelude::*; +use web_sys::IdbDatabase; + +use crate::{ErrorType, Result, RexieBuilder, Transaction, TransactionMode}; + +#[cfg(not(feature = "js"))] +type StoreNames = Vec; + +#[cfg(feature = "js")] +type StoreNames = Array; + +#[cfg_attr(feature = "js", wasm_bindgen)] +pub struct Rexie { + pub(crate) db: IdbDatabase, +} + +#[cfg_attr(feature = "js", wasm_bindgen)] +impl Rexie { + pub fn builder(name: &str) -> RexieBuilder { + RexieBuilder::new(name) + } + + #[cfg_attr(feature = "js", wasm_bindgen(getter))] + pub fn name(&self) -> String { + self.db.name() + } + + pub fn transaction( + &self, + store_names: StoreNames, + mode: TransactionMode, + ) -> Result { + #[cfg(not(feature = "js"))] + let store_names: Array = store_names + .into_iter() + .map(wasm_bindgen::JsValue::from) + .collect(); + + let idb_transaction = self + .db + .transaction_with_str_sequence_and_mode(&store_names, mode.into()) + .map_err(|js_value| { + ErrorType::TransactionOpenFailed + .into_error() + .set_inner(js_value) + })?; + + Ok(Transaction { idb_transaction }) + } + + pub fn close(self) { + self.db.close(); + } +} diff --git a/src/rexie_builder.rs b/src/rexie_builder.rs new file mode 100644 index 0000000..79de9a1 --- /dev/null +++ b/src/rexie_builder.rs @@ -0,0 +1,169 @@ +use std::collections::HashSet; + +use wasm_bindgen::{prelude::*, JsCast}; +use web_sys::{Event, IdbDatabase, IdbFactory, IdbOpenDbRequest, Window}; + +use crate::{ + observer::ResultObserver, utils::set_panic_hook, ErrorType, ObjectStore, Result, Rexie, +}; + +#[cfg_attr(feature = "js", wasm_bindgen)] +pub struct RexieBuilder { + name: String, + version: Option, + object_stores: Vec, +} + +#[cfg_attr(feature = "js", wasm_bindgen)] +impl RexieBuilder { + #[cfg_attr(feature = "js", wasm_bindgen(constructor))] + pub fn new(name: &str) -> Self { + set_panic_hook(); + + Self { + name: name.to_owned(), + version: None, + object_stores: Vec::new(), + } + } + + pub fn version(mut self, version: u32) -> Self { + self.version = Some(version); + self + } + + #[cfg_attr(feature = "js", wasm_bindgen(js_name = "addObjectStore"))] + pub fn add_object_store(mut self, object_store: ObjectStore) -> Self { + self.object_stores.push(object_store); + self + } + + pub async fn build(self) -> Result { + let idb_open_request = get_idb_open_request(&self.name, self.version)?; + + let _upgrade_handler = set_upgrade_handler(&idb_open_request, self.object_stores); + + let observer = ResultObserver::new((), |event| { + let target = event.target().unwrap_throw(); + let request: &IdbOpenDbRequest = AsRef::::as_ref(&target).unchecked_ref(); + + #[allow(clippy::useless_conversion)] + match request.error() { + Ok(Some(exception)) => Err(ErrorType::IndexedDBOpenFailed + .into_error() + .set_inner(exception.into()) + .into()), + Ok(None) => Err(ErrorType::IndexedDBError.into()), + Err(error) => Err(ErrorType::IndexedDBError + .into_error() + .set_inner(error) + .into()), + } + }); + + idb_open_request.set_onsuccess(Some(observer.get_success_callback())); + idb_open_request.set_onerror(Some(observer.get_error_callback())); + + observer.finish().await?; + + let db = idb_open_request + .result() + .map_err(|js_value| { + ErrorType::IndexedDBNotFound + .into_error() + .set_inner(js_value) + })? + .unchecked_into(); + + Ok(Rexie { db }) + } +} + +fn get_window() -> Result { + web_sys::window() + .ok_or_else(|| ErrorType::WindowNotFound.into_error()) + .map_err(Into::into) +} + +fn get_idb_factory() -> Result { + let window = get_window()?; + + window + .indexed_db() + .map_err(|js_value| { + ErrorType::IndexedDBNotSupported + .into_error() + .set_inner(js_value) + })? + .ok_or_else(|| ErrorType::IndexedDBNotSupported.into_error()) + .map_err(Into::into) +} + +fn get_idb_open_request(name: &str, version: Option) -> Result { + let idb_factory = get_idb_factory()?; + + match version { + Some(version) => idb_factory.open_with_u32(name, version), + None => idb_factory.open(name), + } + .map_err(|js_value| { + ErrorType::IndexedDBOpenFailed + .into_error() + .set_inner(js_value) + }) + .map_err(Into::into) +} + +fn set_upgrade_handler( + idb_open_request: &IdbOpenDbRequest, + object_stores: Vec, +) -> Closure { + let upgrade_handler = Closure::once(move |event: Event| { + upgrade_handler(event, object_stores).unwrap_throw(); + }); + + idb_open_request.set_onupgradeneeded(Some(upgrade_handler.as_ref().unchecked_ref())); + + upgrade_handler +} + +fn upgrade_handler(event: Event, object_stores: Vec) -> Result<()> { + let mut store_names: HashSet = object_stores.iter().map(|os| os.name.clone()).collect(); + + let idb_open_request: IdbOpenDbRequest = event + .target() + .ok_or_else(|| ErrorType::EventTargetNotFound.into_error())? + .unchecked_into(); + + let idb: IdbDatabase = idb_open_request + .result() + .map_err(|js_value| { + ErrorType::IndexedDBNotFound + .into_error() + .set_inner(js_value) + })? + .unchecked_into(); + + for object_store in object_stores { + object_store.create(&idb_open_request, &idb)?; + } + + let db_store_names = idb.object_store_names(); + let mut stores_to_remove = Vec::new(); + + for index in 0..db_store_names.length() { + let db_store_name = db_store_names.get(index).unwrap_throw(); + + if store_names.contains(&db_store_name) { + store_names.remove(&db_store_name); + } else { + stores_to_remove.push(db_store_name); + } + } + + for store_name in stores_to_remove { + idb.delete_object_store(&store_name).unwrap_throw(); + } + + Ok(()) +} diff --git a/src/transaction.rs b/src/transaction.rs new file mode 100644 index 0000000..6e43910 --- /dev/null +++ b/src/transaction.rs @@ -0,0 +1,106 @@ +mod index; +mod store; + +pub use self::{index::StoreIndex, store::Store}; + +#[cfg(feature = "js")] +use wasm_bindgen::{prelude::*, throw_str}; +use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt}; +use web_sys::IdbTransaction; + +use crate::{ + observer::{Observer, ResultObserver}, + ErrorType, Result, +}; + +#[cfg(not(feature = "js"))] +#[derive(Debug, Clone, Copy)] +pub enum TransactionMode { + ReadOnly, + ReadWrite, + ReadWriteFlush, + Cleanup, + VersionChange, +} + +#[cfg(feature = "js")] +#[wasm_bindgen] +#[derive(Debug, Clone, Copy)] +pub enum TransactionMode { + ReadOnly = "readonly", + ReadWrite = "readwrite", + ReadWriteFlush = "readwriteflush", + Cleanup = "cleanup", + VersionChange = "versionchange", +} + +impl From for web_sys::IdbTransactionMode { + fn from(mode: TransactionMode) -> Self { + match mode { + TransactionMode::ReadOnly => Self::Readonly, + TransactionMode::ReadWrite => Self::Readwrite, + TransactionMode::ReadWriteFlush => Self::Readwriteflush, + TransactionMode::Cleanup => Self::Cleanup, + TransactionMode::VersionChange => Self::Versionchange, + #[cfg(feature = "js")] + _ => throw_str("invalid transaction mode"), + } + } +} + +#[cfg_attr(feature = "js", wasm_bindgen)] +pub struct Transaction { + pub(crate) idb_transaction: IdbTransaction, +} + +#[cfg_attr(feature = "js", wasm_bindgen)] +impl Transaction { + pub async fn abort(self) -> Result<()> { + let abort_observer = Observer::new(()); + self.idb_transaction + .set_onabort(Some(abort_observer.get_callback())); + + self.idb_transaction.abort().map_err(|js_value| { + ErrorType::TransactionExecutionFailed + .into_error() + .set_inner(js_value) + })?; + + abort_observer.finish().await + } + + pub async fn finish(self) -> Result<()> { + let observer = ResultObserver::new((), |event| { + let target = event.target().unwrap_throw(); + let request: &IdbTransaction = AsRef::::as_ref(&target).unchecked_ref(); + + #[allow(clippy::useless_conversion)] + match request.error() { + Some(exception) => Err(ErrorType::TransactionExecutionFailed + .into_error() + .set_inner(exception.into()) + .into()), + None => Err(ErrorType::IndexedDBError.into()), + } + }); + + self.idb_transaction + .set_oncomplete(Some(observer.get_success_callback())); + self.idb_transaction + .set_onerror(Some(observer.get_error_callback())); + + observer.finish().await + } + + pub fn store(&self, store_name: &str) -> Result { + Ok(Store::new( + self.idb_transaction + .object_store(store_name) + .map_err(|js_value| { + ErrorType::ObjectStoreOpenFailed + .into_error() + .set_inner(js_value) + })?, + )) + } +} diff --git a/src/transaction/index.rs b/src/transaction/index.rs new file mode 100644 index 0000000..02df1f0 --- /dev/null +++ b/src/transaction/index.rs @@ -0,0 +1,197 @@ +#[cfg(feature = "js")] +use std::rc::Rc; + +#[cfg(not(feature = "js"))] +use js_sys::Array; +#[cfg(feature = "js")] +use js_sys::Promise; +#[cfg(feature = "js")] +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsValue; +use web_sys::IdbIndex; + +use crate::{utils::wait_request, ErrorType, KeyRange, Result}; + +#[cfg_attr(feature = "js", wasm_bindgen)] +#[cfg_attr(feature = "js", derive(Clone))] +pub struct StoreIndex { + #[cfg(not(feature = "js"))] + pub(crate) idb_index: IdbIndex, + + #[cfg(feature = "js")] + pub(crate) idb_index: Rc, +} + +impl StoreIndex { + pub fn new(idb_index: IdbIndex) -> Self { + #[cfg(feature = "js")] + let idb_index = Rc::new(idb_index); + + Self { idb_index } + } +} + +#[cfg(not(feature = "js"))] +impl StoreIndex { + pub async fn get(&self, key: impl Into) -> Result { + self.get_js(&key.into()).await + } + + pub async fn get_all(&self) -> Result> { + self.get_all_js() + .await + .map(|array| Array::from(&array).to_vec()) + } + + pub async fn get_all_key_range( + &self, + key_range: KeyRange, + limit: Option, + ) -> Result> { + self.get_all_key_range_js(&key_range, limit) + .await + .map(|array| Array::from(&array).to_vec()) + } + + pub async fn count(&self) -> Result { + let result = self.count_js().await?; + + let count = result + .as_f64() + .map(|count| count as u32) + .ok_or(ErrorType::IndexedDBError)?; + + Ok(count) + } + + pub async fn count_key_range(&self, key_range: &KeyRange) -> Result { + let result = self.count_key_range_js(key_range).await?; + + let count = result + .as_f64() + .map(|count| count as u32) + .ok_or(ErrorType::IndexedDBError)?; + + Ok(count) + } +} + +#[cfg(feature = "js")] +#[wasm_bindgen] +impl StoreIndex { + pub fn get(&self, key: JsValue) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { this.get_js(&key).await }) + } + + #[wasm_bindgen(js_name = "getAll")] + pub fn get_all(&self) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { this.get_all_js().await }) + } + + #[wasm_bindgen(js_name = "getAllKeyRange")] + pub fn get_all_key_range(&self, key_range: KeyRange, limit: Option) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { + this.get_all_key_range_js(&key_range, limit).await + }) + } + + pub fn count(&self) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { this.count_js().await }) + } + + #[wasm_bindgen(js_name = "countKeyRange")] + pub fn count_key_range(&self, key_range: KeyRange) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise( + async move { this.count_key_range_js(&key_range).await }, + ) + } +} + +impl StoreIndex { + async fn get_js(&self, key: &JsValue) -> Result { + let request = self + .idb_index + .get(key) + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let value = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(value) + } + + async fn get_all_js(&self) -> Result { + let request = self + .idb_index + .get_all() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let value = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(value) + } + + async fn get_all_key_range_js( + &self, + key_range: &KeyRange, + limit: Option, + ) -> Result { + let request = match limit { + None => self.idb_index.get_all_with_key(key_range.as_ref()), + Some(limit) => self + .idb_index + .get_all_with_key_and_limit(key_range.as_ref(), limit), + } + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let value = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(value) + } + + async fn count_js(&self) -> Result { + let request = self + .idb_index + .count() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let count = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(count) + } + + async fn count_key_range_js(&self, key_range: &KeyRange) -> Result { + let request = self + .idb_index + .count_with_key(key_range.as_ref()) + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let count = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(count) + } +} diff --git a/src/transaction/store.rs b/src/transaction/store.rs new file mode 100644 index 0000000..4cfa8af --- /dev/null +++ b/src/transaction/store.rs @@ -0,0 +1,331 @@ +#[cfg(feature = "js")] +use std::rc::Rc; + +#[cfg(not(feature = "js"))] +use js_sys::Array; +#[cfg(feature = "js")] +use js_sys::Promise; +#[cfg(feature = "js")] +use wasm_bindgen::prelude::*; +use wasm_bindgen::JsValue; +use web_sys::IdbObjectStore; + +use crate::{utils::wait_request, ErrorType, KeyRange, Result, StoreIndex}; + +#[cfg_attr(feature = "js", wasm_bindgen)] +#[cfg_attr(feature = "js", derive(Clone))] +pub struct Store { + #[cfg(not(feature = "js"))] + pub(crate) idb_store: IdbObjectStore, + + #[cfg(feature = "js")] + pub(crate) idb_store: Rc, +} + +impl Store { + pub fn new(idb_store: IdbObjectStore) -> Self { + #[cfg(feature = "js")] + let idb_store = Rc::new(idb_store); + + Self { idb_store } + } +} + +#[cfg_attr(feature = "js", wasm_bindgen)] +impl Store { + pub fn index(&self, name: &str) -> Result { + let idb_index = self + .idb_store + .index(name) + .map_err(|js_value| ErrorType::IndexOpenFailed.into_error().set_inner(js_value))?; + + Ok(StoreIndex::new(idb_index)) + } +} + +#[cfg(not(feature = "js"))] +impl Store { + pub async fn get(&self, key: impl Into) -> Result { + self.get_js(&key.into()).await + } + + pub async fn get_all(&self) -> Result> { + self.get_all_js() + .await + .map(|array| Array::from(&array).to_vec()) + } + + pub async fn get_all_key_range( + &self, + key_range: KeyRange, + limit: Option, + ) -> Result> { + self.get_all_key_range_js(&key_range, limit) + .await + .map(|array| Array::from(&array).to_vec()) + } + + pub async fn put(&self, key: impl Into, value: impl Into) -> Result<()> { + self.put_js(&key.into(), &value.into()).await + } + + pub async fn put_value(&self, value: impl Into) -> Result<()> { + self.put_value_js(&value.into()).await + } + + pub async fn add(&self, key: impl Into, value: impl Into) -> Result<()> { + self.add_js(&key.into(), &value.into()).await + } + + pub async fn add_value(&self, value: impl Into) -> Result<()> { + self.add_value_js(&value.into()).await + } + + pub async fn delete(&self, key: impl Into) -> Result<()> { + self.delete_js(&key.into()).await + } + + pub async fn count(&self) -> Result { + let result = self.count_js().await?; + + let count = result + .as_f64() + .map(|count| count as u32) + .ok_or(ErrorType::IndexedDBError)?; + + Ok(count) + } + + pub async fn count_key_range(&self, key_range: &KeyRange) -> Result { + let result = self.count_key_range_js(key_range).await?; + + let count = result + .as_f64() + .map(|count| count as u32) + .ok_or(ErrorType::IndexedDBError)?; + + Ok(count) + } + + pub async fn clear(&self) -> Result<()> { + self.clear_js().await + } +} + +#[cfg(feature = "js")] +#[wasm_bindgen] +impl Store { + pub fn get(&self, key: JsValue) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { this.get_js(&key).await }) + } + + #[wasm_bindgen(js_name = "getAll")] + pub fn get_all(&self) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { this.get_all_js().await }) + } + + #[wasm_bindgen(js_name = "getAllKeyRange")] + pub fn get_all_key_range(&self, key_range: KeyRange, limit: Option) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { + this.get_all_key_range_js(&key_range, limit).await + }) + } + + pub fn put(&self, key: JsValue, value: JsValue) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { + this.put_js(&key, &value).await.map(|()| JsValue::UNDEFINED) + }) + } + + #[wasm_bindgen(js_name = "putValue")] + pub fn put_value(&self, value: JsValue) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { + this.put_value_js(&value).await.map(|()| JsValue::UNDEFINED) + }) + } + + pub fn add(&self, key: JsValue, value: JsValue) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { + this.add_js(&key, &value).await.map(|()| JsValue::UNDEFINED) + }) + } + + #[wasm_bindgen(js_name = "addValue")] + pub fn add_value(&self, value: JsValue) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { + this.add_value_js(&value).await.map(|()| JsValue::UNDEFINED) + }) + } + + pub fn delete(&self, key: JsValue) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { + this.delete_js(&key).await.map(|()| JsValue::UNDEFINED) + }) + } + + pub fn count(&self) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { this.count_js().await }) + } + + #[wasm_bindgen(js_name = "countKeyRange")] + pub fn count_key_range(&self, key_range: KeyRange) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise( + async move { this.count_key_range_js(&key_range).await }, + ) + } + + pub fn clear(&self) -> Promise { + let this = self.clone(); + wasm_bindgen_futures::future_to_promise(async move { + this.clear_js().await.map(|()| JsValue::UNDEFINED) + }) + } +} + +impl Store { + async fn get_js(&self, key: &JsValue) -> Result { + let request = self + .idb_store + .get(key) + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let value = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(value) + } + + async fn get_all_js(&self) -> Result { + let request = self + .idb_store + .get_all() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let value = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(value) + } + + async fn get_all_key_range_js( + &self, + key_range: &KeyRange, + limit: Option, + ) -> Result { + let request = match limit { + None => self.idb_store.get_all_with_key(key_range.as_ref()), + Some(limit) => self + .idb_store + .get_all_with_key_and_limit(key_range.as_ref(), limit), + } + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let value = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(value) + } + + async fn put_js(&self, key: &JsValue, value: &JsValue) -> Result<()> { + let request = self + .idb_store + .put_with_key(value, key) + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await + } + + async fn put_value_js(&self, value: &JsValue) -> Result<()> { + let request = self + .idb_store + .put(value) + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await + } + + async fn add_js(&self, key: &JsValue, value: &JsValue) -> Result<()> { + let request = self + .idb_store + .add_with_key(value, key) + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await + } + + async fn add_value_js(&self, value: &JsValue) -> Result<()> { + let request = self + .idb_store + .add(value) + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await + } + + async fn delete_js(&self, key: &JsValue) -> Result<()> { + let request = self + .idb_store + .delete(key) + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await + } + + async fn count_js(&self) -> Result { + let request = self + .idb_store + .count() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let count = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(count) + } + + async fn count_key_range_js(&self, key_range: &KeyRange) -> Result { + let request = self + .idb_store + .count_with_key(key_range.as_ref()) + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await?; + + let count = request + .result() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + Ok(count) + } + + async fn clear_js(&self) -> Result<()> { + let request = self + .idb_store + .clear() + .map_err(|js_value| ErrorType::IndexedDBError.into_error().set_inner(js_value))?; + + wait_request(&request).await + } +} diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..d2b2151 --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,40 @@ +use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt}; +use web_sys::IdbRequest; + +use crate::{observer::ResultObserver, ErrorType, Result}; + +pub fn set_panic_hook() { + // When the `console_error_panic_hook` feature is enabled, we can call the + // `set_panic_hook` function at least once during initialization, and then + // we will get better error messages if our code ever panics. + // + // For more details see + // https://github.com/rustwasm/console_error_panic_hook#readme + #[cfg(feature = "console_error_panic_hook")] + console_error_panic_hook::set_once(); +} + +pub async fn wait_request(idb_request: &IdbRequest) -> Result<()> { + let observer = ResultObserver::new((), |event| { + let target = event.target().unwrap_throw(); + let request: &IdbRequest = AsRef::::as_ref(&target).unchecked_ref(); + + #[allow(clippy::useless_conversion)] + match request.error() { + Ok(Some(exception)) => Err(ErrorType::IndexedDBError + .into_error() + .set_inner(exception.into()) + .into()), + Ok(None) => Err(ErrorType::IndexedDBError.into()), + Err(error) => Err(ErrorType::IndexedDBError + .into_error() + .set_inner(error) + .into()), + } + }); + + idb_request.set_onsuccess(Some(observer.get_success_callback())); + idb_request.set_onerror(Some(observer.get_error_callback())); + + observer.finish().await +} diff --git a/tests/web.rs b/tests/web.rs new file mode 100644 index 0000000..de5c1da --- /dev/null +++ b/tests/web.rs @@ -0,0 +1,13 @@ +//! Test suite for the Web and headless browsers. + +#![cfg(target_arch = "wasm32")] + +extern crate wasm_bindgen_test; +use wasm_bindgen_test::*; + +wasm_bindgen_test_configure!(run_in_browser); + +#[wasm_bindgen_test] +fn pass() { + assert_eq!(1 + 1, 2); +}