Nozbe / WatermelonDB

🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️
https://watermelondb.dev
MIT License
10.62k stars 600 forks source link

Save database from in-memory loki db to IndexedDB manually on web #1329

Open KennanChan opened 2 years ago

KennanChan commented 2 years ago

I am currently using WatermelonDB with loki on web.

I have a page to submit a form. Once the form is submitted, I need to close the page.

The problem is, the database.write() is resolved when the in-memory loki db is updated while the data has not yet been persisted to IndexedDB. Closing the page will result in a data lost.

One approach is to save or flush the loki db to IndexedDB manually and then close the page safely.

I managed to use the code below to solve it for now

function saveDatabase(database: Database): Promise<boolean> {
  return new Promise((resolve) => {
    try {
      const adapter: any = database?.adapter
      const loki = adapter?.underlyingAdapter._driver.loki
      loki.saveDatabase(function(error: any) {
        if (error) {
          console.error(error)
        }
        resolve(!Boolean(error))
      })
    } catch (error) {
      console.error(error)
      resolve(false)
    }
  })
}

It uses the internal fields and will probably be broken in future releases. If a documented saveDatabase() method can be provided on the adapter interface, it will be perfect for those cases.

radex commented 2 years ago

@KennanChan Good idea. I'm OK with having .save() as a method on adapter. I encourage you to submit a pull request with such an improvement

radex commented 1 year ago

@KennanChan any updates?