unjs / unstorage

💾 Unstorage provides an async Key-Value storage API with conventional features like multi driver mounting, watching and working with metadata, dozens of built-in drivers and a tiny core.
https://unstorage.unjs.io
MIT License
1.85k stars 137 forks source link

Multiple Driver Fallback Support #357

Open dalezak opened 11 months ago

dalezak commented 11 months ago

Describe the feature

Is it possible to define multiple drivers with fallback logic?

For example use IndexDB if supported, else fallback to use LocalStorage.

This is something that LocalForage supports, which is great to have this "use best option" functionality.

localForage.config({
  driver: [
    this.unstorage.INDEXEDDB,
    this.unstorage.WEBSQL,
    this.unstorage.LOCALSTORAGE
  ]
});

Is this currently possible with unstorage? If not could this be implemented with a custom driver?

Additional information

dalezak commented 11 months ago

One idea is a simple try-catch, try using indexedDbDriver, if it fails then fallback to localStorageDriver.

try {
  this.unstorage = createStorage({
    driver: indexedDbDriver({
      storeName: "app"
    })
  });
}
catch (error) {
  this.unstorage = createStorage({
    driver: localStorageDriver()
  });
}

Will this work? Is there a better option?

eligao commented 10 months ago

I suggest implementing a few common policies like read-through/write-through etc. see: https://www.prisma.io/dataguide/managing-databases/introduction-database-caching I've recently implemented a TieredStorage driver in my own project, it's under tests and I'll create a PR when it's ready.