idb_sys/
factory.rs

1use js_sys::Reflect;
2use wasm_bindgen::{JsCast, JsValue};
3use web_sys::IdbFactory;
4
5use crate::{DatabaseRequest, Error};
6
7/// Lets applications asynchronously access the indexed databases.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Factory {
10    inner: IdbFactory,
11}
12
13impl Factory {
14    /// Gets an instance of [Factory] from `global` scope.
15    pub fn new() -> Result<Factory, Error> {
16        let inner = Reflect::get(&js_sys::global(), &JsValue::from("indexedDB"))
17            .map_err(Error::IndexedDbNotFound)?
18            .dyn_into()
19            .map_err(Error::IndexedDbNotFound)?;
20        Ok(Self { inner })
21    }
22
23    /// Attempts to open a connection to the named database with the specified version. If the database already exists
24    /// with a lower version and there are open connections that don’t close in response to a `versionchange` event, the
25    /// request will be blocked until they all close, then an upgrade will occur. If the database already exists with a
26    /// higher version the request will fail.
27    pub fn open(&self, name: &str, version: Option<u32>) -> Result<DatabaseRequest, Error> {
28        match version {
29            Some(version) => self.inner.open_with_u32(name, version),
30            None => self.inner.open(name),
31        }
32        .map(Into::into)
33        .map_err(Error::IndexedDbOpenFailed)
34    }
35
36    /// Attempts to delete the named database. If the database already exists and there are open connections that don’t
37    /// close in response to a `versionchange` event, the request will be blocked until they all close.
38    pub fn delete(&self, name: &str) -> Result<DatabaseRequest, Error> {
39        self.inner
40            .delete_database(name)
41            .map(Into::into)
42            .map_err(Error::IndexedDbDeleteFailed)
43    }
44}
45
46impl From<IdbFactory> for Factory {
47    fn from(inner: IdbFactory) -> Self {
48        Self { inner }
49    }
50}
51
52impl From<Factory> for IdbFactory {
53    fn from(factory: Factory) -> Self {
54        factory.inner
55    }
56}
57
58impl TryFrom<JsValue> for Factory {
59    type Error = Error;
60
61    fn try_from(value: JsValue) -> Result<Self, Self::Error> {
62        value
63            .dyn_into::<IdbFactory>()
64            .map(Into::into)
65            .map_err(|value| Error::UnexpectedJsType("IdbFactory", value))
66    }
67}
68
69impl From<Factory> for JsValue {
70    fn from(value: Factory) -> Self {
71        value.inner.into()
72    }
73}