idb/
factory.rs

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